Magento: Add checkout/cart_sidebar block programmatically in custom controller

There are many ways to create a block within Magento and there is very little documentation to compare the methods of adding one programmatically through a Magento controller vs creating one via Magento's XML structure.

Quick Tip: Actions in layout xml configs are just a block method call.

In following example I show how to call "checkout/cart_sidebar" and the different equivalents of xml vs a controller

<block type     = "checkout/cart_sidebar"
       name     = "cart_sidebar"
       as       = "cartExplorer"
       template = "checkout/cart/sidebar.phtml"
       before   = "-">
<action method="addItemRender">
    <type>configurable</type>
    <block>checkout/cart_item_renderer_configurable</block>
    <template>checkout/cart/sidebar/default.phtml</template>
</action>


<!-- Programmatically create the block -->
<?php
    $this->getLayout()
         ->createBlock('checkout/cart_sidebar', 'cart_sidebar')
         ->setTemplate('checkout/cart/sidebar.phtml');
         ->addItemRender(
             'configurable',
             'checkout/cart_item_renderer_configurable',
             'checkout/cart/sidebar/default.phtml'
         )

?>


<!-- This is if it was already created in a layout.xml file -->
<?php

$this->getLayout()
     ->getBlock('cart_sidebar')
     ->addItemRender(
         'configurable',
         'checkout/cart_item_renderer_configurable',
         'checkout/cart/sidebar/default.phtml'
     )

?>
Hope this helps!!

One thought on “Magento: Add checkout/cart_sidebar block programmatically in custom controller”

Leave a Reply