Magento – Modify custom option of product in cart

cartcheckoutmagento-1.9PHPquote

I have this code in checkout/cart/item/default.phtml

$allProductOptions = $_item->getProduct()->getTypeInstance(true)>getOrderOptions($_item->getProduct());
    $productOptions = $allProductOptions['info_buyRequest'];

And in $productOptions I have custom option saved from product page: $productOptions['my_option']. How can I update that option?

Best Answer

In the code above, $_item refers to an instance of Mage_Sales_Model_Quote_Item, so you can alter the buyRequest with the code below:

$buyRequest = $_item->getOptionByCode('info_buyRequest');
$buyRequestArr = unserialize($buyRequest->getValue());
$buyRequestArr['whatever_you_like'] = 'some_value';
$buyRequest->setValue(serialize($buyRequestArr))->save();

However I'd definitely not advise altering the buyRequest from a phtml file, if you want to add data in to the buyRequest or change existing data, you should do so via an event observer by listening for checkout_cart_product_add_after, which supplied you with the quote item, so you can set data on the buyRequest like so:

public function checkoutCartProductAddAfter(Varien_Event_Observer $observer)
{
    $item = $observer->getQuoteItem();
    $buyRequestArr = array();
    if ($buyRequest = $item->getProduct()->getCustomOption('info_buyRequest')) {
        $buyRequestArr = unserialize($buyRequest->getValue());
    }
    $buyRequestArr['whatever_you_like'] = 'some_value';
    $buyRequest->setValue(serialize($buyRequestArr))->save();
}
Related Topic