Search code examples
twigshopware6

How to access previous orders of a customer in Twig template?


I am working on a Shopware 6 plugin and need to modify a Twig template to include conversion tracking parameters based on whether a customer has previous paid orders. Specifically, I need to set the tsCategory parameter to 2 if the customer has previous paid orders, otherwise it should be 1.

Here is the relevant part of my index.html.twig file:

{% block layout_head_javascript_tracking_swag_after_finish %}
        {% set tsCategory = 1 %}
        <script>
            {% for item in page.order.lineItems.elements %}
                {% if item.type == PRODUCT_LINE_ITEM_TYPE %}
                        var tsOrderID = "{{ page.order.orderNumber|escape('js') }}";
                        var tsCategory = "{{ tsCategory }}";
            {% endfor %}
        </script>
    {% endif %}
{% endblock %}

How can I access and check if a customer has previous paid orders in this Twig template?

Any guidance on how to achieve this in Shopware 6 would be greatly appreciated!


Solution

  • Create a new file called CheckoutFinishSubscriber.php in the <plugin root>/src/Subscriber/ directory.

    File contents CheckoutFinishSubscriber.php:

    <?php declare(strict_types=1);
    
    namespace Swag\BasicExample\Subscriber;
    
    use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates;
    use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
    use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
    use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
    use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NotFilter;
    use Shopware\Core\System\SalesChannel\SalesChannelContext;
    use Shopware\Storefront\Page\Checkout\Finish\CheckoutFinishPageLoadedEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class CheckoutFinishSubscriber implements EventSubscriberInterface
    {
        public function __construct(
            private readonly EntityRepository $orderRepository
        ) {}
    
        public static function getSubscribedEvents(): array
        {
            return [
                CheckoutFinishPageLoadedEvent::class => 'onCheckoutFinish',
            ];
        }
    
        public function onCheckoutFinish(CheckoutFinishPageLoadedEvent $event): void
        {
            $salesChannelContext = $event->getSalesChannelContext();
            $page = $event->getPage();
            $currentOrderId = $page->getOrder()->getId();
    
            $paidOrderCount = $this->findPaidOrderCountByCustomer($currentOrderId, $salesChannelContext);
            $tsCategory = $paidOrderCount > 0 ? 2 : 1;
    
            $page->assign([
                'tsCategory' => $tsCategory
            ]);
        }
    
        private function findPaidOrderCountByCustomer(string $currentOrderId, SalesChannelContext $salesChannelContext): int
        {
            $criteria = new Criteria();
            $criteria->addFilter(new NotFilter(
                NotFilter::CONNECTION_AND,
                [new EqualsFilter('order.id', $currentOrderId)]
            ));
            $criteria->addFilter(new EqualsFilter('order.salesChannelId', $salesChannelContext->getSalesChannelId()));
            $criteria->addFilter(new EqualsFilter('order.orderCustomer.customerId', $salesChannelContext->getCustomer()->getId()));
            $criteria->addAssociation('transactions.stateMachineState');
            $criteria->addFilter(new EqualsFilter('transactions.stateMachineState.name', OrderTransactionStates::STATE_PAID));
    
            return $this->orderRepository->search($criteria, $salesChannelContext->getContext())->getTotal();
        }
    }
    

    Register subscriber in the <plugin root>/src/Resources/config/services.xml file.

    File contents services.xml:

    <?xml version="1.0" ?>
    
    <container xmlns="http://symfony.com/schema/dic/services"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    
        <services>
            <service id="Swag\BasicExample\Subscriber\CheckoutFinishSubscriber">
                <argument type="service" id="order.repository"/>
                <tag name="kernel.event_subscriber"/>
            </service>
        </services>
    </container>
    

    Now you can use the variable {% set tsCategory = page.tsCategory %} in the <plugin root>/src/Resources/views/storefront/page/checkout/finish/index.html.twig file.

    Additional documentation that will help you: