0

I am using Magento Enterprise 2.2.10 and I am wanting to show out of stock products and want to have show at the end of the category collection. I thought I could use the event: catalog_product_collection_load_before but that does not seem to exist in Magento 2 but this event does work: catalog_product_collection_load_after

If I use the catalog_product_collection_load_after event I can add the fields to the collection ordering but they get added the order default category ordering and does not accomplish what I want to do.

Any ideas how I can go ordering products like this since that event does not fire?

Is there a way to replace the order by query instead of add to it?

Using the event catalog_product_collection_load_after I was able to modify the collection query to order the data the way I want but it does not have any affect on the display of the products in the category.

This is what I came up with which does generate the correct query but why does it not change the order of the product on the category?

$collection                           
    ->getSelect()                     
    ->joinLeft(                       
        array('_inventory_table' => $c
        "_inventory_table.product_id =
        array('is_in_stock')          
    )                                 
    ->reset('order')                  
    ->order('is_in_stock DESC')       
    ->order('cat_index_position ASC');
  • I got this working by overriding the Magento catalog model layer instead of using the event – Trevor Orr Oct 21 '19 at 16:56
  • please update your answer – jafar pinjar Feb 25 at 3:25
  • Hi Trevor, can you update your answer? – saran Mar 9 at 10:12
0

This is what ended up working for me.

public function afterGetProductCollection(\Magento\Catalog\Model\Layer $subject, $result)
{
    $fieldOrders = $result->getSelect()->getPart('order');
    $curOrders = array();

    foreach($fieldOrders as $fieldOrder) {
        if ($fieldOrder[0] !== 'is_salable') {
            $curOrder = $fieldOrder[0];
            if (count($curOrder) > 1) {
                $curOrder .=  ' ' . $fieldOrder[1];
            }

            array_push($curOrders, $curOrder);              
        }
    }

    $result
        ->getSelect()
        ->reset('order')
        ->order('is_salable DESC');

    foreach($curOrders as $curOrder) {
        $result
            ->getSelect()
            ->order($curOrder);
    }

    return $result;
}
| improve this answer | |

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.