Can’t Add Child Block to Product List in Magento – How to Fix

blockslayoutlayout-update

I'm trying to add a block to the product listing:

<?xml version="1.0"?>
<layout version="0.1.0">
    <catalog_category_view translate="label">
        <reference name="product_list">
            <remove name="product_list_toolbar"/>
            <block type="core/template" name="helloworld" as="helloworld" template="helloworld.phtml"/>
        </reference>
        <reference name="footer">
            <block type="core/template" name="helloworld" as="helloworld" template="helloworld.phtml"/>
        </reference>
    </catalog_category_view>
</layout>

In catalog/product/list.phtml I have this:

<?php Zend_Debug::dump($this->getSortedChildren()); ?>
<?php echo $this->getChildHtml('helloworld'); ?>

In page/html/footer.phtml I have this:

<?php Zend_Debug::dump($this->getSortedChildren()); ?>
<?php echo $this->getChildHtml('helloworld'); ?>

Note that I only added <remove name="product_list_toolbar"/> so that I can test if my reference to product_list works correctly, by seeing if product_list_toolbar is removed from the sorted children list. It is.

So what I now have is identical code in the product list and the footer, and it only works in the footer. After doing some digging, I can't find any instance of a block being added to product_list other than product_list_toolbar. So, is there something about this block that makes adding children not work?

Best Answer

The issue here is the order in which the blocks are specified in the layout XML.

catalog_category_view is technically the right handle, BUT in that handle the product_list block doesn't exist (yet!).

The product_list block only gets created in the catalog_category_default and catalog_category_layered handles. (And those handles are specified later in the XML than catalog_category_view.)

In short, when all the layout XML gets merged, your reference to product_list won't get executed, because it doesn't exist yet at that point.

The solution is to add your block in both catalog_category_default and catalog_category_layered, OR, create your own custom handle, add your block in that handle, and use the <update> directive to include your handle in catalog_category_default and catalog_category_layered.

Hope that worked for you.

Related Topic