I want to get a collection of all the items in cart currently.
How can I do this ? Any suggestions will be appreciated.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this community$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
$productName = $item->getProduct()->getName();
$productPrice = $item->getProduct()->getPrice();
}
in $cart
you got all collection of cart item and if you want to get product id,name you can get from using foreach loop
I found another solution. The following code works for me.
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
$productId = $item->getProductId();
// Do something more
}
$item->getProduct()
... Every time you think about using ->load() in magento you can count on bad performance, sometimes there aren't any other option really but this is not the case here..
There are several methods that work in a different way:
$items = Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
Returns a quote item collection with all items associated to the current quote.
$items = Mage::getSingleton('checkout/cart')->getItems();
This is a shortcut for the method above, but if there is no quote it returns an empty array, so you cannot rely on getting a collection instance.
$items = Mage::getSingleton('checkout/cart')->getQuote()->getAllItems();
Loads the item collection, then returns an array of all items which are not marked as deleted (i.e. have been removed in the current request)
$items = Mage::getSingleton('checkout/cart')->getQuote()->getAllVisibleItems();
Loads the item collection, then returns an array of all items which are not marked as deleted AND do not have a parent (i.e. you get items for bundled and configurable products but not their associated children). Each array item corresponds to a displayed row in the cart page.
Choose what fits your needs best. In most cases the last method is what you need, but unfortunately Magento only provides it as array and not as collection.
Note that Mage::getSingleton('checkout/cart')->getQuote()
and Mage::getSingleton('checkout/session')->getQuote()
are interchangable.
$items =Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
foreach($items as $item) {
echo 'ID: '.$item->getProductId().'<br />';
echo 'Name: '.$item->getName().'<br />';
echo 'Sku: '.$item->getSku().'<br />';
echo 'Quantity: '.$item->getQty().'<br />';
echo 'Price: '.$item->getPrice().'<br />';
echo "<br />";
}
best way to get the all item in cart
Below code is used for getting cart items
$cart = new Mage_Checkout_Model_Cart();
$cart->init();
foreach ($cart->getItems() as $item) {
// we can wrap our request in this IF statement
if (!$item->getParentItemId()) {
}
}