0

I have a plugin for the afterSetCollection method, which is hung on the Magento\Catalog\Block\Product\ProductList\Toolbar -> setCollection method. But for some reason, sorting occurs by the price, color and others fields, but by the field in the discount model object, sorting does not occur. But nevertheless, products with this filtering parameter are displayed on the page. What could be the problem?

$collection->setOrder('price', 'desc'); - Work
$collection->setOrder('color', 'asc'); - Work
$collection->setOrder('discount', 'asc'); - Does not work
1
  • Are you implementing discount sorting by amount or percentage? and can you please make sure that "discount" field is present in the collection or not? If its present, then technically it should be work same as price and color. Jan 28, 2023 at 6:22

1 Answer 1

0

First, You need to make sure that whatever field(discount) you need to sort that field is included in the query. I think the price & color fields already included the collection query that's why it's working fine.

You can check your field included in the collection query by using the below line.

echo $collection->getSelect();exit;

If your field (Discount) is not included in the collection query then include using the following line of code & then sort.

$collection->addAttributeToSelect(['discount']);
$collection->setOrder('discount', 'ASC'); // You can change the sort direction with the ASC OR DESC.

Below collection sorting example with the full code.

$collection = $layer->getProductCollection();
$collection->addAttributeToSelect(['discount']);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->addAttributeToFilter('visibility',4);
$collection->setOrder('discount', 'ASC');

Please note if you have a custom column then you need to join your custom column table with the product collection to select that column and then need to apply the sorting.

The above approach works for progmatically but you want to achieve it through the admin panel then go through the mentioned answer in the below reference link. Sort collection by discount

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.