0

I want to sort product collection by Custom Price attribute. enter image description here here is my code

Here is my code, what is the problem here, i dont understand?

<?php
namespace Vendor\Module\Model\VisualMerchandiser\Sorting;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\VisualMerchandiser\Model\Sorting\SortAbstract;
use Magento\VisualMerchandiser\Model\Sorting\SortInterface;
class CustomPriceBottom extends SortAbstract implements SortInterface
{
    /**
     * @param Collection $collection
     * @return Collection
     */
    public function sort(
        Collection $collection
    ): Collection {
        $collection->addAttributeToSelect('*')
            ->setOrder('custom_price', 'DESC');
        
//        $collection->getSelect()
//            ->distinct('entity_id')
//            ->reset(Zend_Db_Select::ORDER)
//            ->order('custom_price ' . CollectionAlias::SORT_ORDER_ASC);
        return $collection;
    }
    /**
     * @return string
     */
    public function getLabel(): string
    {
        return __("Custom Price Bottom");
    }
}

2 Answers 2

1

You didn't reset collection order before apply your custom order

In your case you can extends from \Magento\VisualMerchandiser\Model\Sorting\AttributeAbstract and implements getSortField, getSortDirection and getLabel

You can see as example \Magento\VisualMerchandiser\Model\Sorting\Name\Descending

0
0
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Model\VisualMerchandiser\Sorting;

use Magento\VisualMerchandiser\Model\Sorting\AttributeAbstract;

class CustomPriceBottom extends AttributeAbstract
{
    /**
     * @return string
     */
    public function getLabel(): string
    {
        return __("Custom Price Bottom");
    }

    /**
     * @return string
     */
    protected function getSortField(): string
    {
        return 'custom_price';
    }

    /**
     * @return string
     */
    protected function getSortDirection(): string
    {
        return $this->descOrder();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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