Latheesan
Latheesan

Reputation: 24116

Get cart contents from my custom module in Magento

In my magento, I have added a product to cart - so I see the following on the checkout page:

enter image description here

I have a custom module with a TestController with a IndexAction where I want to retrieve the current contents of basket for custom processing. This will be used to provide a "get delivery cost estimate" type functionality.

I.e. customer will add bunch of items into basket (as guest), click a button on front end and it takes them to our module where they will enter the destination country and postcode and we will do some custom processing to let the customer know what the estimated delivery cost is going to be.

I tried to retrieve the basket contents like this:

$cart_contents = Mage::helper('checkout')->getQuote();
foreach ($cart_contents->getItemsCollection() as $item) {
   var_dump($item->getName());
}
exit;

This does not return anything.

I also tried a different approach:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
echo "<pre>";
foreach ($cartItems as $item) {
    print_r($item->getData());
}
exit;

This is also returning nothing.

Bear in mind; this is a guest checkout (i.e. customer is not logged in).

To test there is a valid quote; I did the following:

echo "<pre>";
print_r(Mage::helper('checkout')->getQuote()->getData());
echo "<hr>";
print_r(Mage::getSingleton('checkout/session')->getQuote()->getData());
exit;

This is what I get back:

Array
(
    [store_id] => 5
    [is_checkout_cart] => 1
    [remote_ip] => 90.xxx.xxx.xxx
    [x_forwarded_for] => 90.xxx.xxx.xxx
)
Array
(
    [store_id] => 5
    [is_checkout_cart] => 1
    [remote_ip] => 90.xxx.xxx.xxx
    [x_forwarded_for] => 90.xxx.xxx.xxx
)

Upvotes: 0

Views: 1145

Answers (2)

Qaisar Satti
Qaisar Satti

Reputation: 2762

This is Magento code for getting the cart item; try it:

$cart = Mage::getModel('checkout/cart')->getQuote();

if($cart->getAllItems()):
    foreach ($cart->getAllItems() as $item):
        echo $item->getProduct()->getName();
    endforeach;
endif;

Upvotes: 0

RD Mage
RD Mage

Reputation: 103

You can use following script to get cart items on your custom controller action.

$itemsCollection = Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection();
$itemsVisible = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
<?php foreach($items as $item) { ?>     
    <p class="product-name"><a href="<?php echo $item->getProductUrl();?>"><?php echo $item->getName(); ?></a></p>
    <span class="price"><?php echo Mage::helper('core')->currency($item->getPrice(),true,false);?></span>
    <span class="qty">Qty: <?php echo $item->getQty(); ?> </span>
<?php } ?>

Upvotes: 0

Related Questions