Magento – Programmatically adding configurable products to the cart with SCP

cartconfigurable-productmagento-1.9

I am using the SCP extension so that prices are taken from the simple product and not the configurable.
I am using url approach to add product in the cart

checkout/cart/add?product=10940&qty=1&super_attribute[134]=22

This url adds product into cart but price is taken from first associated product only. same price is rendered in all associated products.

Best Answer

Can you try below code ?

$_product = $this->getProduct();
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
// check if something is returned
if (!empty(array_filter($parentIds))) {
    $pid = $parentIds[0];

    // Collect options applicable to the configurable product
    $configurableProduct = Mage::getModel('catalog/product')->load($pid);
    $productAttributeOptions = $configurableProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($configurableProduct);
    $options = array();

    foreach ($productAttributeOptions as $productAttribute) {
        $allValues = array_column($productAttribute['values'], 'value_index');
        $currentProductValue = $_product->getData($productAttribute['attribute_code']);
        if (in_array($currentProductValue, $allValues)) {
            $options[$productAttribute['attribute_id']] = $currentProductValue;
        }
    }

    // Get cart instance
    $cart = Mage::getSingleton('checkout/cart'); 
    $cart->init();
    // Add a product with custom options
    $params = array(
        'product' => $configurableProduct->getId(),
        'qty' => 1,
        'super_attribute' => $options
    );
    $request = new Varien_Object();
    $request->setData($params);
    $cart->addProduct($configurableProduct, $request);
    $session = Mage::getSingleton('customer/session');
    $session->setCartWasUpdated(true);
    $cart->save();
}

Main thing about adding configurable product to cart is what data/options are passed to super_attribute.

For more information please check this out.

Hope this helps.

Related Topic