Magento – How to add Simple product with custom options to cart

cartcustom-optionsproduct

I have a simple product with custom options. After popup, I select custom options of this product, and click add to cart.

I get params like that: product=167&options%5B4%5D=10&qty=1.

Now I want to add product to cart programmatically, how can I do it?

Best Answer

please check the Mage_Checkout_CartController and addAction() inside, you will find everything you need ;)

$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();
        $related = $this->getRequest()->getParam('related_product');

        /**
         * Check product availability
         */
        if (!$product) {
            $this->_goBack();
            return;
        }

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

        $cart->save();

        $this->_getSession()->setCartWasUpdated(true);
        /**
         * @todo remove wishlist observer processAddToCart
         */
        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')->htmlEscape($product->getName()));
                $this->_getSession()->addSuccess($message);
            }
            $this->_goBack();
        }