3

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?

2 Answers 2

4

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();
}
0
public function __construct(
       
        \Magento\Framework\Serialize\Serializer\Json $serialize
    )
    {
      
        $this->serialize = $serialize;
    } 
 public function execute(\Magento\Framework\Event\Observer $observer)
    {
       
        $item = $observer->getQuoteItem();  
        $buyRequest = $item->getOptionByCode('info_buyRequest');
        $buyRequestArr =  $this->serialize->unserialize($buyRequest->getValue());
        $buyRequestArr['tester'] = 1;
        $buyRequest->setValue($this->serialize->serialize($buyRequestArr))->save(); 
        return $this;
    }
 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.