Magento 2 – How to Set Default Direction in Catalog Search Result

catalogsearchmagento2

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.

Best Answer

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.