Close

Not a member yet? Register now and get started.

lock and key

Sign in to your account.

Account Login

Forgot your password?

Magento Adding Custom Options in Shopping Cart

28 May Posted by in Magento | Comments
Magento Adding Custom Options in Shopping Cart

I recently had a client who needed the ability to add and modify custom options that were already in the shopping cart. This is useful for users who often change their mind or want to get as far in the checkout process as possible before being bothered with options. I don’t want to get into too much detail, but I can give you the key functions:

The first set of functions are used below.

//Get the checkout Session
$session = Mage::getSingleton('checkout/session');
//Iterate through all Items in Cart
foreach ($session->getQuote()->getAllItems() as $item){

$program = Mage::getModel('catalog/product')->load($item->getProduct()>getId());
$options = $program->getOptions();

//Get the option you want to modify
foreach($options as $option) {
if ($option->getTitle() == 'OPTION NAME HERE'){
$optionId= $option->getId();
}
}
//Now get the Custom Options in cart
$productOptions= $item->getProduct()->getTypeInstance(true)->
getOrderOptions($item->getProduct());
}

So $productOptions is an array that contains all the current options. Now, to modify a current entry or add a new one, all you need to do is clear the cart and iterate through $productOptions to add them all back to the cart. I have written some pseudo code below.

$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();

for ( $counter = 0; $counter <  count($productOptions['options']); $counter++) {
if($productOptions['options'][$counter]['label'] != 'OPTION NAME') {
$arr['options'][$productOptions['options'][$counter]['option_id']] = $productOptions['options'][$counter]['option_value'];
}
}
$arr['options'][option id of custom option] = 'New Value';
$cart->addProduct($program, $arr);
$cart->save();

And there you have it!

 


Leave a comment