3
votes

I have tried to add the products to cart using custom module. Below is the code i used

    $product_id = $this->getRequest()->getParam('product');

    $product = Mage::getModel('catalog/product')->load($product_id);

    $param = array( 'product' => $product->getId(), 'qty' => 2,'options["'.$option_id.'"]' => $option_type_id );

  $cart = Mage::getModel('checkout/cart')->init();
  $cart->addProduct($product, new Varien_Object($param));
  Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
  $cart->save();

I can add the products name, quantity to cart using product id, But i cannot able to add the products custom options in cart.

Please give me a hand on this.

Thanks, Prakash

1

1 Answers

3
votes

You're so close! The main thing that you need to change is your $param, as it is not structured the way Magento would like. This should do the trick:

$param = array(
    'product' => $product->getId(),
    'qty' => 2,
    'options' => array(
                        $option_id => $option_value,
                        $option_id2 => $option_value2,
                      ),
);

Note that any required custom options on your product will need to have values to avoid a fatal error whilst adding to the cart. Also, no need to cast $param as a Varien_Object - Magento understands the array just fine.