Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento - get cart items for a given product id

Tags:

magento

I try to get the cart items for a given product;

I have tried this code :

$product = Mage::getModel('catalog/product')
    ->setStoreId(Mage::app()->getStore()->getId())
    ->load('2784');

$quote = Mage::getSingleton('checkout/cart')->getQuote();
$cartItems = $quote->getItemByProduct($product);
foreach ($cartItems as $item) {
    echo $item->getId()."<br/>";
}

but it don't gives anything.

How can I modify my code to use "getItemByProduct" in the right form ?

Thanks for help.

like image 799
Ahmed Ala Dali Avatar asked Dec 05 '11 10:12

Ahmed Ala Dali


People also ask

What is order item data in Magento 2?

Item data or product data collection in Magento 2 means showing you the number of items present in your store. The below code describes how to use item id to get order item collection in Magento 2.

How to get product attributes in Magento 2?

During the cart display admin always prefers displaying the information of the product. This illustration will be helping you to show how to get product attributes in Magento 2. Firstly, you will be required to declare at catalog_attributes.xml file where you can simply define custom attribute values with the help of quote_item group.

How does tier pricing work in Magento?

Magento then applies a 10% discount to the remaining total of the products in the cart. In the following example, tier prices has been established for product 24-UG01 and 24-UG05, as shown in the following table:

What is the difference between Magento 1 and Magento 2?

Magento 2 has a lot more to offer than Magento 1. If you have an eCommerce site running on Magento 2 platform then knowing how to get item data from your online store is a thing you should know about. This post is going to teach you how to retrieve this.


3 Answers

getItemByProduct() returns the first matching Mage_Sales_Model_Quote_Item so there is no need for an extra loop.

$item = $quote->getItemByProduct($product);
if ($item !== false) echo $item->getId();
like image 198
clockworkgeek Avatar answered Oct 07 '22 17:10

clockworkgeek


I'd use

foreach ($quote->getItems() as $item) {
    if ($item->getProductId() == $product->getId()) {
        print_r($item->getData());
    }
}
like image 1
Max Avatar answered Oct 07 '22 18:10

Max


You can not use getItemByProduct() function on the checkout/cart or checkout/quote model as that method is of the sales/quote model.

You can find this method at the Mage_Sales_Model_Quote class. so it is used withe sales/quote. hope this is useful.

like image 1
Namita sheth Avatar answered Oct 07 '22 18:10

Namita sheth