Magento – Programmatically inject header mini cart

blocksce-1.9.0.1checkout

I'm trying to update my header mini cart dynamically by creating a new block, I've tried several ways including:

$this->loadLayout();
$block = $this->getLayout()->createBlock(
    'Mage_Checkout_Block_Cart',
    //'checkout/cart', // OR 'Mage_Checkout_Block_Cart'
    'minicart_content',
    array('template' => 'ajax/checkout/cart/sidebar/default.phtml')
);

$this->getLayout()->getBlock('content')->append($block);
//Release layout stream... lol... sounds fancy
$this->renderLayout();

And also

$block = $this->getLayout()->createBlock('checkout/cart')->setTemplate('ajax/checkout/cart/sidebar/default.phtml')->toHtml();

They always come back empty, I can get it to bring back static content fine. Any ideas please?

Best Answer

In your module/controller/CartController.php action (or another) :

$data["cart_sidebar"] = $this->getLayout()
->createBlock('checkout/cart_sidebar')
->setTemplate('checkout/cart/minicart/items.phtml')
->addItemRender("default", "checkout/cart_item_renderer", "checkout/cart/minicart/default.phtml")
->addItemRender("simple", "checkout/cart_item_renderer", "checkout/cart/minicart/default.phtml")
->addItemRender("grouped", "checkout/cart_item_renderer_grouped", "checkout/cart/minicart/default.phtml")
 ->addItemRender("configurable", "checkout/cart_item_renderer_configurable", "checkout/cart/minicart/default.phtml")
 ->toHtml();

You can use json to serialize your data.

Then have just to put in your js :

jQuery(".block.block-cart").html(data.cart_sidebar);

If you want upgrade cart qty, serialize it too ;)

Related Topic