0

I'm writing an EventSubscriber for the config entity of the domain module. My goal is to insert some data in its config on preSave event (it becomes from the patch for D9).

Here is my code from ConfigEventSubscriber class of my custom module:


namespace Drupal\custom_module\EventSubscriber;

use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Drupal\domain\Entity\Domain;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

 class ConfigEventSubscriber implements EventSubscriberInterface {

   public function __construct(Domain $domain) {
     $this->domain = $domain;
   }
   /**
   * {@inheritdoc}
   *
   * @return array
   * The event names to listen for, and the methods that should be executed.
   */
  public static function getSubscribedEvents() {
    return [
      ConfigEvents::PRESAVE => 'configPreSave'
    ];
  }

  /**
   * React to a config object being saved.
   *
   * @param \Drupal\Core\Config\ConfigCrudEvent $event
   *   Config crud event.
   */
  public function configPreSave(ConfigCrudEvent $event) {
    $config = $event->getConfig();
    $domain_id = $config->getOriginal('id');
    if ($config->getStorage()->listAll('domain.record.')) {
      $this->domain->addDependencyTrait('module', 'country_path');
      $this->domain->setThirdPartySetting('country_path', 'domain_path', $domain_id);
    }
  }
 }

Here is my services.yml file:

services:
  Drupal\custom_module\EventSubscriber\ConfigEventSubscriber:
    tags:
      - { name: 'event_subscriber' }
    arguments: ['@domain.element_manager']

It throws an error that instance of DomainElementManager given, but Domain entity expected and it's logical, as far as I'm including $domain instance of Domain in my construct. But, I need the Domain class to use these methods:

addDependency, setThirdPartySettings.

So, my question is how to use these methods correctly in the context of my task?

Any help is appreciated.

4
  • If you can't get the Domain directly as service, can you get from an existing service? E.g., if the domain manager has a getDomain() method, you could rewrite your class to inject the manager and pull out the Domain in the constructor.
    – beltouche
    Sep 22, 2021 at 16:35
  • Unfortunately, it doesn't have such a method. This method exists in DomainAliasInterface, but it is not declared in services.yml of its module as well.
    – Yaroslav
    Sep 22, 2021 at 16:43
  • 1
    Even if you don't have the methods of a fully loaded domain entity, you should still be able to get and set all config settings, also third party settings: $config->get('third_party_settings')
    – 4uk4
    Sep 23, 2021 at 7:29
  • Thanks, it helped me a lot. I've used $config->set() method and pushed necessary data.
    – Yaroslav
    Sep 23, 2021 at 14:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.