Magento – Add Simple Product to Cart Instead of Configurable Product

cartconfigurable-productevent-observersimple-product

I want to prevent configurable products from ending up in the cart. I want to add their simple product equivalent to the cart.

Despite this being a fairly normal request, I haven't found anything that is doing this.

I currently have an observer set up to work on checkout_cart_add_product_complete
checkout_cart_add_product_complete

I'm able to manipulate the cart from here (add, remove items), but I can't remove a configurable product (nor its options).

Does anyone know how this is possible?

Observer.php

class Mymodule_Addtocartredirect_Model_Customizablereplace {
    public function replaceItems($observer) {
        $quote   = Mage::getSingleton('checkout/session')->getQuote();
        $storeId = Mage::app()->getStore()->getStoreId();

        foreach ($quote->getAllItems() as $item) {
            $result = array();
            Mage::log("We have a product! " . $item->getSku(),null,"test.log");
            if($item->getOptionByCode('simple_product')) {
                $childProduct = $item->getOptionByCode('simple_product')->getProduct()->getId();
                Mage::log("We have ".$childProduct,null,"test.log");
            }

            if ($option = $item->getOptionByCode('simple_product')) {
                $cartHelper = Mage::helper('checkout/cart')->getCart();
                $quantity = $item->getQty();
                $childProduct = $option->getProduct();
                Mage::log("Child Product: ".$childProduct->getSku()." (".$childProduct->getId().")",null,"test.log");
                $cartHelper->removeItem($item->getId());
                $cartHelper->addItem($childProduct->getId(),$quantity);
            }
        }
        $quote->collectTotals()->save();
    }
}

Best Answer

Few days back,I did the same,by creating a custom module Create a module and in the CartController.php file, create the following:

<?php 
    require_once 'Mage/Checkout/controllers/CartController.php';
    class Yourname_Mymodule_CartController extends Mage_Checkout_CartController
    {
        public function addAction()
        {
            if (!$this->_validateFormKey()) {
                $this->_goBack();
                return;
            }
            $cart   = $this->_getCart();
            $params = $this->getRequest()->getParams();
            try {
                if (isset($params['qty'])) {
                    $filter = new Zend_Filter_LocalizedToNormalized(
                        array('locale' => Mage::app()->getLocale()->getLocaleCode())
                    );
                    $params['qty'] = $filter->filter($params['qty']);
                }

                $product = $this->_initProduct();
                $child = $product->getTypeInstance(true)->getProductByAttributes($params['super_attribute'], $product);
                $related = $this->getRequest()->getParam('related_product');


                if (!$child) {
                    $this->_goBack();
                    return;
                }

                $cart->addProduct($child, $params);
                if (!empty($related)) {
                    $cart->addProductsByIds(explode(',', $related));
                }

                $cart->saveSpecial();

                $this->_getSession()->setCartWasUpdated(true);


                Mage::dispatchEvent('checkout_cart_add_product_complete',
                    array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
                );

                if (!$this->_getSession()->getNoCartRedirect(true)) {
                    if (!$cart->getQuote()->getHasError()) {
                        $message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($child->getName()));
                        $this->_getSession()->addSuccess($message);
                    }
                    $this->_goBack();
                }
            } catch (Mage_Core_Exception $e) {
                if ($this->_getSession()->getUseNotice(true)) {
                    $this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
                } else {
                    $messages = array_unique(explode("\n", $e->getMessage()));
                    foreach ($messages as $message) {
                        $this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
                    }
                }

                $url = $this->_getSession()->getRedirectUrl(true);
                if ($url) {
                    $this->getResponse()->setRedirect($url);
                } else {
                    $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
                }
            } catch (Exception $e) {
                $this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
                Mage::logException($e);
                $this->_goBack();
            }
        }
    }

Create a new save function

<?php
class Yourname_Mymodule_Model_Cart extends Mage_Checkout_Model_Cart
{
    public function save()
    {
        Mage::dispatchEvent('checkout_cart_save_before', array('cart'=>$this));

        $this->getQuote()->getBillingAddress();
        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
        $this->getQuote()->collectTotals();
        $this->getQuote()->save();
        $this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());
        Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
        foreach($this->getQuote()->getAllItems() as $_item)
        {
            $_item->setCustomPrice($_item->getPrice());
            $_item->setRowTotal($_item->getPrice()*$_item->getQty());
            $_item->setBaseRowTotal($_item->getBasePrice()*$_item->getQty());
            $_item->setOriginalCustomPrice($_item->getCustomPrice());
            $_item->setCalculationPrice($_item->getCustomPrice());
        }
        return $this;
    }

    public function saveSpecial()
    {
        Mage::dispatchEvent('checkout_cart_save_before', array('cart'=>$this));

        $this->getQuote()->getBillingAddress();
        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
        $this->getQuote()->collectTotals();
        $this->getQuote()->save();
        $this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());

        Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
        return $this;
    }
}

Done!!