Magento 1 – How to Pass Data to getChildHtml() or Call Method on Child Block

blockslayoutmagento-1

I want to be able to pass data to the getChildHtml() call. The reason is, the output of the block is dependant upon a product type. So i want to pass the product to the getChildHtml so that it can decide on the output.

I am doing this inside template/checkout/cart/item/default.phtml.

Ideally, the call would look like:

echo $this->getChildHtml('child_block_name', $_item);

Then my block can get the product type from the item and display the correct output.

Since it is definitely not possible to pass this data to getChildHtml – how else can this type of behaviour be achieved without having to rewrite the core block

The two solutions i currently have are as follows (neither very attractive):

1 – Create a helper and access the html output via the helper instead of letting a block and template render it ala $this->helper('my_module')->getItemHtml($_item);

2 – Access the child block and setData on it inside the template:

 $this->getChild('child_name')->setData('item', $_item);
 echo $this->getChildHtml('child_name')

I think in terms of the Magento architecture, number 2 is the lesser of two evils, but it is darn ugly looking inside a template.

Best Answer

You can add a method on the parent block to fetch the child depending on the product type (I've seen this kind of logic a couple of times in core or something similar):

class ParentBlock 
{
    public function getIntuitiveNameChild($item)
    {
        return $this->getChild("intuitive_child")
                    ->setProductType($item->getProductType()) 
                    // You can also decide the product type in this setter, in the Child block.
                    ->setItem($item);
    }

    public function getIntuitiveNameChildDinamically($item)
    {
        return $this->getChild("intuitive_child_" . $item->getProductType())
                    ->setItem($item); 
    }    
}

// parent tpl
// i suggest you avoid getChildHtml(), unless you're certain that methods won't need to be called from the tpl
echo $this->getIntuitiveNameChild($_item)
          // ->someOtherMethod()
          ->toHtml();

Still, seeing how you modify the layout xml to add children blocks, you may be interested in how Magento decided to work with rendering markup depending on product types in Mage_Sales_Block_Items_Abstract::getItemHtml() and Mage_Checkout_Block_Cart_Abstract::getItemHtml().

Related Topic