Overview
In this post, we will discuss how to listen to the event before and after the write operation in Shopware6. When you create your custom plugins then you need to perform some additional logic with existing events.
Listen to the event
In this topic, we listen to the customer register event before and after the write operation in Shopware6, so let’s assume we need to add some additional information about the user and persist in another table.
First of all, we find all possible customer events in customerEvent class, here we use CUSTOMER_WRITTEN_EVENT for adding some custom logic.
<?php declare(strict_types=1);
namespace Webkul\TestExample\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class WebkulEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CustomerEvent::CUSTOMER_WRITTEN_EVENT => 'onCustomerWritten',
];
}
public function onCustomerWritten(EntityWrittenEvent $event): void
{
// Do stuff
}
}
Reading the event data
If you want to change the payload of the customer data before the persists in the database. Shopware provides a PreWriteValidationEvent which is trigged before the write result set is generated.
Suppose we need to add custom data in custom entity before the customer create, then we listen PreWriteValidationEvent in our subscriber.
<?php declare(strict_types=1);
namespace Swag\BasicExample\Service;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\ChangeSetAware;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\InsertCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\UpdateCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class WebkulEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
PreWriteValidationEvent::class => 'triggerChangeSet',
CustomerEvent::CUSTOMER_WRITTEN_EVENT => 'onCustomerWritten',
];
}
public function triggerChangeSet(PreWriteValidationEvent $event): void
{
foreach ($event->getCommands() as $command) {
// Do stuff
}
}
public function onCustomerWritten(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $result) {
$changeSet = $result->getChangeSet();
// Do stuff
}
}
}
In the above code, we subscribe to the CUSTOMER_WRITTEN_EVENT for adding custom logic or stuff. In the first method, we subscribe to the PreWriteValidationEvent which is trigged before the write result set is generated.
Multi-Seller Marketplace Plugin
Thanks for reading this blog, I hope it will help you. Happy coding 🙂
Be the first to comment.