Reputation: 25
namespace Drupal\ta3mal_utilities\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Entity\EntityTypeEvents;
use Drupal\Core\Entity\EntityTypeEvent;
class EntityEvents implements EventSubscriberInterface {
public function onCreate(EntityTypeEvent $event) {
//Do things on creation
}
public function onUpdate(EntityTypeEvent $event) {
dd('on update now');
}
public function onDelete(EntityTypeEvent $event) {
//Do things on delete
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [];
$events[EntityTypeEvents::CREATE][] = ['onCreate', 1];
$events[EntityTypeEvents::UPDATE][] = ['onUpdate', 1];
$events[EntityTypeEvents::DELETE][] = ['onDelete', 1];
return $events;
}
}
I have included this in the services file as well, the getSubscribedEvents is called but it doe not reach the updated one, any help ? Thank you.
Upvotes: 2
Views: 1634
Reputation: 2581
EntityTypeEvents::XXX
is triggered when entity types
are being created/updated/deleted. Looking at your classname, I'm assuming you want the entity
events. Currently it's not possible to do this with Drupal Core and the events combo you're trying to implement. Referring to this issue: https://www.drupal.org/project/drupal/issues/2551893 you could also try the contributed module mentioned in the ticket, but I don't have any experience with that module, so mileage may vary.
If you want entity events you will need to stick with the old hook style system.
The hooks you're looking for are:
Full reference here in the Drupal docs: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/8.8.x
Another thing that I noticed that might help you in the future when implementing event listeners is that you declared all your subscribe events with priority 1. It could be that you're putting the priority too high up in the hierarchy. If you don't need to expliytidly execute your code before any other Drupal Modules or core functionality, I would omit the priority and just leave it empty so the default value (0) will be used, this will make sure your event is added to the end of the list. The order of execution could mean you're breaking other modules/core functionality, so always be careful with that.
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[EntityTypeEvents::CREATE][] = ['onCreate'];
$events[EntityTypeEvents::UPDATE][] = ['onUpdate'];
$events[EntityTypeEvents::DELETE][] = ['onDelete'];
return $events;
}
Smalle code nit, you can also omit $events = [];
since it's not needed to declare an empty array.
Upvotes: 4