Steve Robbins
Steve Robbins

Reputation: 13812

Use a template/block in a helper

I have a helper with this method to get the items in a customer's cart

public function getCartData()
{
    //Get cart DATA
    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $cartItems = $quote->getAllVisibleItems();
    $items = '';
    foreach ($cartItems as $item) {
        $items .= $item->getId() . " ";
    }
    return $items;
}

But what I want to do is replace this line

$items .= $item->getId() . " ";

With an instance of template/checkout/cart/sidebar/default.phtml

How would I go about this? The method is being called in an ajax controller. I want to update the user's cart without a page refresh, but it needs to be formatted.

Upvotes: 0

Views: 3444

Answers (1)

Rick Buczynski
Rick Buczynski

Reputation: 837

So you want to render what's in the template for each $item in the loop?

If you look at app/design/frontend/base/default/layout/checkout.xml, you will see the original sidebar block defined:

<block type="checkout/cart_sidebar" name="cart_sidebar" template="checkout/cart/sidebar.phtml" before="-">
    <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/sidebar/default.phtml</template></action>
    <action method="addItemRender"><type>grouped</type><block>checkout/cart_item_renderer_grouped</block><template>checkout/cart/sidebar/default.phtml</template></action>
    <action method="addItemRender"><type>configurable</type><block>checkout/cart_item_renderer_configurable</block><template>checkout/cart/sidebar/default.phtml</template></action>
</block>

I'm not sure if you'll be able to get away with simply using the item renderer, checkout/cart_item_renderer (which is what you want based on your question), but let's try it. So you'll have to programmatically create an instance of the block, feed it the item, assign it your template, and output its HTML to your variable.

$items='';
foreach($cartItems as $item) {
    $items.=Mage::app()->getLayout()->createBlock('checkout/cart_item_renderer')
            ->setItem($item)
            ->setTemplate('checkout/cart/sidebar/default.phtml')
            ->toHtml();
}

Notice how after creating the block, we set the item. That's important, because if you examine the template you'll see at the top that it calls:

<?php $_item = $this->getItem() ?>

Give this a try and see if it helps!

Upvotes: 1

Related Questions