I'm trying to add a configurable product to the cart, but while it's not throwing any Exceptions, the cart is still empty.
I've used this code before without problems, so I'm not sure if it's something to do with the version of Magento I'm using.
The code I'm using is:
$post = $this->getRequest()->getPost();
$session = Mage::getSingleton('customer/session');
$attr = array_keys($post['sa']);
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
foreach ($post['sa'][$attr[0]] as $optId){
try {
if (abs($post['qty'][$optId]) > 0){
$product = Mage::getModel('catalog/product')->load($post['product']);
$this->getRequest()->setParam('product',$post['product']);
$this->getRequest()->setParam('super_attribute',array(
$attr[0] => $optId
));
$options = array(
"product"=>$post['product'],
"super_attribute"=>array(
$attr[0] => $optId
),
"qty"=>$post['qty'][$optId]
);
$opts = new Varien_Object();
$opts->setData($options);
var_dump($opts);
$cart->addProduct($product, $opts);
$cart->save();
}
} catch (Exception $e){
var_dump($e);
}
}
$cart->save(); // save the cart
$cart->setCartWasUpdated(true);
$pdts = $cart->getAllVisibleItems();
var_dump($pdts);
die("??");
So I'd expect to get a cart with 6 items in it (3 products, configurable + simple), however I'm getting null instead - as you can see from the below, which also shows the $opts object I'm trying to pass:
object(Varien_Object)[507]
protected '_data' =>
array (size=3)
'product' => string '86' (length=2)
'super_attribute' =>
array (size=1)
179 => string '20' (length=2)
'qty' => string '1' (length=1)
protected '_hasDataChanges' => boolean true
protected '_origData' => null
protected '_idFieldName' => null
protected '_isDeleted' => boolean false
protected '_oldFieldsMap' =>
array (size=0)
empty
protected '_syncFieldsMap' =>
array (size=0)
empty
object(Varien_Object)[663]
protected '_data' =>
array (size=3)
'product' => string '86' (length=2)
'super_attribute' =>
array (size=1)
179 => string '19' (length=2)
'qty' => string '2' (length=1)
protected '_hasDataChanges' => boolean true
protected '_origData' => null
protected '_idFieldName' => null
protected '_isDeleted' => boolean false
protected '_oldFieldsMap' =>
array (size=0)
empty
protected '_syncFieldsMap' =>
array (size=0)
empty
object(Varien_Object)[678]
protected '_data' =>
array (size=3)
'product' => string '86' (length=2)
'super_attribute' =>
array (size=1)
179 => string '17' (length=2)
'qty' => string '3' (length=1)
protected '_hasDataChanges' => boolean true
protected '_origData' => null
protected '_idFieldName' => null
protected '_isDeleted' => boolean false
protected '_oldFieldsMap' =>
array (size=0)
empty
protected '_syncFieldsMap' =>
array (size=0)
empty
null
??
Any help would be apprciated!
You can add using following code.