I need a help ASAP related to sort by functionality in magento 2
1] I need to remove default sort by options.
2] I need to add my own sorting options.
I tried a custom module in which I have override the block file
vendor/magento/module-catalog/Block/Product/ProductList/Toolbar.php
In which I have override the setCollection() function
I have define custom options like:
class Toolbar extends \Magento\Catalog\Block\Product\ProductList\Toolbar {
public function setCollection($collection) {
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
$limit = (int) $this->getLimit();
if ($limit) {
$this->_collection->setPageSize($limit);
}
if ($this->getCurrentOrder()) {
switch ($this->getCurrentOrder()) {
case 'created_at_desc':
$this->_collection
->addAttributeToSort('name');
//->order('e.created_at ASC');
break;
case 'created_at_asc':
$this->_collection
->addAttributeToSort('name');
//->order('e.created_at DESC');
break;
case 'price_low_to_high':
$this->_collection
->addAttributeToSort('price');
//->order('price_index.price ASC');
break;
case 'price_high_to_low'://need to change
$this->_collection
->addAttributeToSort('price');
break;
case 'model'://need to change
$this->_collection
->getSelect()
->joinLeft(
['admin' => $collection->getTable('cataloginventory_stock_status')], 'e.entity_id = admin.product_id')->where('admin.stock_status = 1');
break;
case 'new_to_old':
$this->_collection
->getSelect()
->order('e.created_at DESC');
break;
case 'old_to_new':
$this->_collection
->getSelect()
->order('e.created_at ASC');
break;
default:
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
break;
}
}
return $this;
}
}
I get the 'old_to_new' and 'new_to_old' code and its working fine,
but need the other remaining following options too. I tries all possible options but can't get the result.
This are the following remaining options I need :
-created_at_desc--- name by asc(A-Z)
-created_at_asc--- name by desc(Z-A)
-price_low_to_high--- price low to high
-price_high_to_low--- price high to low
Thanks
Best Answer
You need to a custom extension with plugins, I followed this
app/code/Company/CustomSort/etc/di.xml
Now we need to define our config labels and new options.
app/code/Company/CustomSort/Plugin/Model/Config.php
We declared all required options, now we need to implement these options and overwrite Magento default sorting method.
app/code/Company/CustomSort/Plugin/Product/ProductList/Toolbar.php
Now you need to run
and it should work like charm.Happy coding.