I have a EventSubscriber
which I want to trigger before the entity is saved (to alter the title). But I can't figure why it doesn't work. I got back the projet, do the migration from D8 to D9. Is it possible that is came from the D9 migration ?
I could simply add the hook_entity_presave
in a module, but I guess it's cleaner to add that in an EventSubscriber
my_module.entity_event_subscriber:
class: Drupal\my_module\EventSubscriber\EntityEventSubscriber
arguments: ['@entity_type.manager','@entity_field.manager']
tags:
- { name: event_subscriber }
Here my event
<?php
namespace Drupal\my_module\EventSubscriber;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\hook_event_dispatcher\Event\Entity\EntityPresaveEvent;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EntityEventSubscriber implements EventSubscriberInterface {
private $em;
private $entityFieldManager;
public function __construct(EntityTypeManagerInterface $em, EntityFieldManagerInterface $entityFieldManager) {
$this->em = $em;
$this->entityFieldManager = $entityFieldManager;
}
public static function getSubscribedEvents() {
return [
HookEventDispatcherInterface::ENTITY_PRE_SAVE => 'entitySave',
];
}
/**
*
*/
public function entitySave(EntityPresaveEvent $event) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $event->getEntity();
$entity_type_id = $entity->getEntityTypeId();
$bundle = $entity->bundle();
if (in_array($entity_type_id, ['node', 'node_custom'])) {
/// logic
}
}
}