Search code examples
phpsymfonyeventsshopware6subscriber

how to detect an order placed with shopware 6.5 (event subscribers) and also get its present state


Hello I am trying to detect when a new order comes into my store using shopware 6.5

this is what I am doing :

OrderEvents::ORDER_WRITTEN_EVENT => 'OnOrderReceived',

public function OnOrderReceived(EntityWrittenEvent $event) { if ($event->getEntityName() === 'order') {

        $writtenEntities = $event->getWriteResults();


        foreach ($writtenEntities as $writeResult) {
            // Get the entity data from the write result
            $entityData = $writeResult->getPayload();

            // Get the order ID from the entity data
            $orderId = $entityData['id'];
            $orderNumber = $entityData['orderNumber'];

            // $this->logger->info('Orders is created, the order id is : ' . $orderId . ' and order number : ' . $orderNumber);

        }


    }

}`

With this I am able to get the order Id and number, but I can't seem to capture the present state of the order e.g "open". please how do I do this?


Solution

  • The OrderEvents::ORDER_WRITTEN_EVENT is a pretty low level technical event, so it is quite hard to get the infos out there that you need.

    You should better listen to the \Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent as that event gives you easy access to the info you need:

    public static function getSubscribedEvents(): array
    {
       return [
           CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
       ];
    }
    
    public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
    {
        $orderId = $event->getOrderId();
        $state = $event->getOrder()->getStateMachineState()->getName();
    }