0

I want to sort my list.phtml and catalogsearch by availability. Mean that when category page or search result page loads, first show "in stock" product and at the end show out of stock items. Don't want to show or sort on "sort by" function. want to show from load. by default i set "sort by" to lowest price but need to show lowest price and availability is in stock.

0

I didn't test this code, but you can do something like the following:

    <?php

use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\InventoryIndexer\Indexer\IndexStructure;
use Magento\InventoryIndexer\Model\StockIndexTableNameResolverInterface;

/**
 * Adapt adding and applying is in stock field to collection for Multi Stocks.
 */
class AddIsInStockSortToCollection
{
    /**
     * @var StockIndexTableNameResolverInterface
     */
    private $stockIndexTableProvider;

    /**
     * @param StockIndexTableNameResolverInterface $stockIndexTableProvider
     */
    public function __construct(
        StockIndexTableNameResolverInterface $stockIndexTableProvider
    ) {
        $this->stockIndexTableProvider = $stockIndexTableProvider;
    }

    /**
     * @param Collection $collection
     * @param int $stockId
     * @return void
     */
    public function sortProductCollection($collection, int $stockId)
    {
        $tableName = $this->stockIndexTableProvider->execute($stockId);

        $collection->getSelect()->join(
            ['inventory_in_stock' => $tableName],
            'e.sku = inventory_in_stock.sku',
            []
        )->order(['inventory_in_stock.' . IndexStructure::IS_SALABLE => \Zend_Db_Select::SQL_DESC ]);
    }
}

(The code is based on the Magento core code in vendor/magento/module-inventory-catalog/Model/ResourceModel/AddIsInStockFieldToCollection.php)

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.