Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Simple Product from Configurable in Cart

I'm trying to load the simple products that have been added to a customer's cart, but when I retrieve the items, it's showing the parent configurable.

$cart = Mage::getSingleton('checkout/cart');
$productIds = array();

foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
    $productIds[] = $item->getProduct()->getId();
}

var_dump($productIds);

For instance, this will return all the same configurable id when I've added a small, medium, and large to my cart. How can I get the individual simple products? I'm trying to retrieve an attribute value that's set on the simple product level.

like image 388
Steve Robbins Avatar asked Aug 02 '13 23:08

Steve Robbins


1 Answers

After taking a look at how Magento renders the items in your cart on the checkout/cart page, I was able to find this in app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Configurable.php

/**
 * Get item configurable child product
 *
 * @return Mage_Catalog_Model_Product
 */
public function getChildProduct()
{
    if ($option = $this->getItem()->getOptionByCode('simple_product')) {
        return $option->getProduct();
    }
    return $this->getProduct();
}

So, applying it to the snippet in the question, it would be

foreach ($cart->getQuote()->getAllVisibleItems() as $item) {
    $productId = $item->getProduct()->getId();
    if ($option = $item->getOptionByCode('simple_product')) {
        $productId = $option->getProduct()->getId();
    }
    $productIds[] = $productId;
}
like image 138
Steve Robbins Avatar answered Oct 04 '22 04:10

Steve Robbins