Magento - 在观察者中更改产品自定义选项值

时间:2015-12-02 17:04:56

标签: magento options

如何在产品添加到购物车时更改产品自定义选项值?我的伪代码 -

public function generatePreviewImage(Varien_Event_Observer $obs) {
    // Get the order item
    $orderItem = $obs->getOrderItem();

    // Get product options with values
    $productOptions = $orderItem->getProductOptions()

    // Set new value
    $productOptions['options'][$index]['option_value'] = 'my new value';

    // Update options and save orderItem
    $orderItem->setProductOptions($productOptions);
    $orderItem->save();
}

1 个答案:

答案 0 :(得分:0)

我的解决方案

// Add new info_buyRequest option
$item = $obs->getQuoteItem();
$product = $item->getProduct();
$options = $item->getOptions();

foreach ($options as $option){
    // Select buy request options
    if($option->getCode() == 'info_buyRequest') {
        $infoBuyRequestOption = $option;

        $unserializedInfoBuyRequest = unserialize($infoBuyRequestOption->getValue());

        // Set my new option
        $unserializedInfoBuyRequest['preview'] = 'My new preview image';

        // Store new options
        $infoBuyRequestOption->setValue(serialize($unserializedInfoBuyRequest));
        $item->setOptions($options)->save();
        Mage::getSingleton('checkout/cart')->save();
        break;
    }
}

// And then in cart rendering view
$preview = unserialize($this->getProduct()->getCustomOption('info_buyRequest')->getValue())['preview'];

// In admin panel
$preview = $_item->getProductOptionByCode('info_buyRequest')['preview'];