Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default sorting on product listing in shopware 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')
            );
        }
    }
}


like image 870
Maltisch Avatar asked Nov 07 '22 06:11

Maltisch


1 Answers

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').

like image 160
admi22 Avatar answered Nov 13 '22 03:11

admi22