简体   繁体   中英

Magento - How can I add or remove a custom option from a product in the cart?

I'm trying to add or remove custom options from a product in the cart. The custom options are defined against the product itself in the back end, I'm not trying to make up a new custom option dynamically or anything like that. All of my custom options are single checkboxes, in case it makes a difference.

I'm using an observer on checkout_cart_update_items_after and looping through Mage::getSingleton('checkout/session')->getQuote()->getAllItems() . I can see which items currently have a custom option selected using

$orderOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
if ( isset($orderOptions['info_buyRequest']['options']) )
    // cart item has options selected.

In the first instance I'd really like to be able to remove these custom options. I expected to be able to find something like $item->removeOption($optionId); , but I can't find any way of doing this.

In the second instance I'd really like to be able to add a custom option to an item. I've tried various ways of doing this including $item->addOption(array('code'=>$optionCode, 'value'=>1)); .

I can't get either to work, and I'm sure I'm just missing something quite simple. Can you help?

If you want to specify custom product options on-the-fly on quote items (Ex:adding Delivery date with each product in the orders), you can make use of an observer toadd a custom option.

Example:

<controller_action_predispatch_checkout>
<observers>
<options_observer>
<class>YOUR_CLASS_NAME</class>
<method>setProductInfo</method>
</options_observer>
</observers>
</controller_action_predispatch_checkout>


$deliveryDate = $prId['delivery_date'];
if (!empty($deliveryDate)) {
$opt['options'] = array($optionID => $deliveryDate);
$request->setParams($opt);
}
return $this;

Another way to add option is

$item->addOption(array(
    'code' => 'additional_options',
    'value' => serialize($additionalOptions),
));

Suppose you have below option

$option = array(
    'title' => 'Auto Date & Time',
    'type' => 'date_time',
    'is_require' => 1,
    'sort_order' => 0,
    'is_delete' => '',
    'previous_type' => '',
    'previous_group' => '',
    'price' => '0.00',
    'price_type' => 'fixed',
    'sku' => ''
);

Fetch $product->getOptionInstance() directly

$product->getOptionInstance()->addOption($option);

$product->setHasOptions(true); //mention that the product has custom options

To delete the custom option:

if($product->getOptions() != ''{
  foreach ($product->getOptions() as $opt){
     $opt->delete(); 
   } 
 $product->setHasOptions(0)->save();
}

Hope it helps !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM