3

Magento 2 uses default "asc" ordenation for category page and Layered Navigation. But in catalog search result page, the default direction is setted to "desc" and I've debugged the code, I've found the method configureToolbar in \Magento\Catalog\Block\Product\ListProduct these lines:

$dir = $this->getDefaultDirection();
if ($dir) {
   $toolbar->setDefaultDirection($dir);
}

I have debugged this, following the call stack until I reach the DataObject.php, where the default_direction property is setted, but I don't know where this value came from, so how can I change this default direction in my search result page? Thanks in advance.

1

Classic Magento issue.

One will go through colledge and then further self educate for a decade for all the programming principles, patterns and best practices and what not.

Eventually, one will debug and will get stuck with a question like this, myself included of course. Magento certainly does not make things easy for debug.

But, I think I got that code that sets the direction. I sadly present to you

Magento\CatalogSearch\Block\Result

and its method

public function setListOrders()
{
    $category = $this->catalogLayer->getCurrentCategory();
    /* @var $category \Magento\Catalog\Model\Category */
    $availableOrders = $category->getAvailableSortByOptions();
    unset($availableOrders['position']);
    $availableOrders['relevance'] = __('Relevance');

    $this->getListBlock()->setAvailableOrders(
        $availableOrders
    )->setDefaultDirection(
        'desc'
    )->setDefaultSortBy(
        'relevance'
    );

    return $this;
}

Now, you can perhaps change portions of it to

->setDefaultDirection(
    'hardcoded-direction'
)

and when you hit your debug point

$dir = $this->getDefaultDirection();

and in the configureToolbar method from ListProduct you will see that $dir value is hardcoded-direction.

You would expect from Magento to not hard code parameters for such an important eCommerce feature as the search is, but still, there it is.

2
  • Hi Marjan, thanks for answering, I've walked over and around this code and just couldn't see it haha. But I think I've noticed why magento default is "desc" here, when you use the "relevance" sort, the most relevant results goes to the end, tha's why it is setted as "desc", I'm trying to set to "asc" only if is NOT "relevance" sort, but your answer fits my question, thankyou. – lpFranz Sep 10 '18 at 13:04
  • You are welcome! :) – Marjan Sep 10 '18 at 14:14

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.