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')
);
}
}
}
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With