Change default sorting on product listing in shopware 6
Asked Answered
M

1

6

I have created a new Sorting after this documentation .

    <argument>a-sorting</argument>
    <argument>New Sorting</argument>
    <argument type="collection">
        <argument key="product.markAsTopseller">desc</argument>
        <argument key="product.updatedAt">desc</argument>
    </argument>
    <tag name="shopware.sales_channel.product_listing.sorting" />
</service>

You can select now the new Sorting in the frontend and it is working fine. But i don't know how to set this sorting as page default. I mean the product list should be sorted initially after the page is loaded.

I solved it with ProductListingCriteriaEvent and ProductListingResultEvent

<?php declare(strict_types=1);

namespace MyPlugin\Storefront\Subscriber;

use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ProductSubscriber implements EventSubscriberInterface
{

    /**
     * @inheritDoc
     */
    public static function getSubscribedEvents()
    {
        return [
            ProductListingCriteriaEvent::class  => 'handleRequest',
            ProductListingResultEvent::class    => 'handleResult'
        ];
    }

    /**
     * @param ProductListingResultEvent $event
     */
    public function handleResult(ProductListingResultEvent $event): void
    {
        $request = $event->getRequest();

        /* Sorting is not selected in frontend */
        if (!$request->get('order')) {
            $event->getResult()->setSorting('a-sorting');
        }
    }

    /**
     * @param ProductListingCriteriaEvent $event
     */
    public function handleRequest(ProductListingCriteriaEvent $event): void
    {
        $request = $event->getRequest();
        $criteria = $event->getCriteria();

        /* Sorting is not selected in frontend */
        if (!$request->get('order')) {
            $criteria->resetSorting();
            $criteria->addSorting(
                new FieldSorting('markAsTopseller', 'DESC'),
                new FieldSorting('updatedAt', 'DESC')
            );
        }
    }
}


Mcevoy answered 1/7, 2020 at 15:17 Comment(3)
Thanks, I bundled part of this up in a little plugin and also added a configuration option; github.com/elgentos/shopware-default-sort-orderSon
Thanks for adding your solution!Floatation
How often is it that you find the perfect solution for your problem, copy paste ready. Thank you!Chemurgy
D
1

Excellent post, thanks @Maltisch!

I want to add a small detail: It seems like they changed the query name from 'sort' to 'order' somewhere around the 6.2 version. In my case I had to use $request->get('sort').

Dealing answered 21/7, 2020 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.