I recently had the requirement to change the layout in Magento for a category if it didn’t have any products in it. The issue came from using a two column left layout. This meant that when no products were in the category, there was a blank left column – as no filters were being created.
To combat this, when a category didn’t have any products in it, I wanted to change to a 1 column layout.
Having done some research, I stumbled upon this post – Magento: change layout if category has no products however, unfortunately, the answer didn’t work – controller_action_predispatch_catalog_category_default
with a function that could grab the current product list and check if it was empty. We use ->count()
so that the collection isn’t loaded here.
A solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Branded3_Emptycategory_Model_Observer { public function zeroproducts(Varien_Event_Observer $observer) { $controller = $observer->getAction(); //limit to the product view page if ($controller->getFullActionName() != 'catalog_category_view') { return; } $_productCollection = $observer->getEvent() ->getLayout()->getBlock('product_list')->getLoadedProductCollection(); if (!$_productCollection->count()) { $observer->getEvent()->getLayout() ->getBlock('root') ->setTemplate('page/1column.phtml'); } } } |
Image Credit: Cinnamon Sugar Snickerdoodle Cookies
Comment or tweet @douglasradburn