one magento developer

my experiences about magento

Magento 2 sort in-stock product at the first

so the question is how we can sort product at the categories by stock status.

Magento does not have any config for this because of that we should write several line the first, we need to add an observer to change default sorting. Let me add XML to define the observer classes.

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
   <event name="catalog_block_product_list_collection">
       <observer name="stockLast" instance="ChalakSoft\StockSort\Observer\Sort" />

Okay let me look at the code.we use event to say to the magento that we have an observer

the name determine name of the event that we want use it.there is we use `


The second name is the name of our observer. It should be unique.
instance is our observer class

now we can create our observer class

namespace ChalakSoft\StockSort\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Event\Observer;
use Magento\Catalog\Block\Product\ProductList\Toolbar as CoreToolbar;
class Sort implements ObserverInterface
   protected $scopeConfig;
   protected $_storeManager;
   protected $coreToolbar;
   public function __construct(
       ScopeConfigInterface $scopeConfig,
       StoreManagerInterface $storeManager,
       CoreToolbar $toolbar
       $this->scopeConfig = $scopeConfig;
       $this->_storeManager = $storeManager;
       $this->coreToolbar = $toolbar;
   public function execute(Observer $observer)
       $collection = $observer->getEvent()->getData('collection');
       try {
           $websiteId = 0;
           $stockId = 'stock_id';
               array('_inv' => $collection->getResource()->getTable('cataloginventory_stock_status')),
               "_inv.product_id = e.entity_id and _inv.website_id=$websiteId",
           $collection->addExpressionAttributeToSelect('in_stock', 'IFNULL(_inv.stock_status,0)', array());
           $collection->getSelect()->order('in_stock DESC');
           //code for Filter Price Low to High or High to Low with stock filter.
           if ($this->coreToolbar->getCurrentOrder() == 'price') {
               $direction = $this->coreToolbar->getCurrentDirection();
               $collection->getSelect()->order("min_price $direction");
       } catch (\Exception $e) {
       return $this;

i think all thing is clear.if you have any question feel free to write a new comment

Leave a Reply

Your email address will not be published. Required fields are marked *.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>