Sometimes we need to add products into cart programmatically in controller. Below is the code which you can use to add product to cart.
1) For Simple Products
If you are working in magento controller and wants to add a simple product programmatically then here is the code: Suppose our product id value stored in $productId.
// Below code will create instance of cart $cart = Mage::getModel(‘checkout/cart’); // This will initialize cart $cart->init(); // Get the product collection by passing product id $productCollection = Mage::getModel(‘catalog/product’)->load($productId);
This product collection will be required as we have to pass it at the time of adding product to cart.
For adding the product we have to call addProduct() function. In this function we have to pass two parameters first is productcollection and second is an array. This array contains product id and quantity which we are going to add to cart.
// Add product to cart $cart->addProduct($productCollection, array( ‘product_id’ => $productId, ‘qty’ => 1); As now we have added our simple product to cart. Now only one thing remainig and that is save the cart. // Save cart $cart->save();
2) For Configurable Product
Suppose we want to add a configurable product which have custom options. In that case we will product id, option id and optoin value. Lets took an example for suppose our product is T-Shirt and its coming in color variant. Each color has its different option id and option value.
Same thing goes with configurable product also like create instance of cart and then initialize it and create product collection.
// Get cart and product collection $cart = Mage::getModel(‘checkout/cart’); $cart->init(); $productCollection = Mage::getModel(‘catalog/product’)->load($productId);
Now the part came where we need to add product to cart which is different from simple type product. Here in array we have to pass options array also. This options array contains the selected option id and option value for product.
// Add configurable product to cart $cart->addProduct($productCollection , array( ‘product_id’ => $productId, ‘qty’ => 1, ‘options’ => array( $optionId => $optionValue));
Like this we can add configurable product to cart. Atlast we need to save the cart.