Is it possible to update a product custom option value from an order? I know it is possible when items are in cart (before checkout), but I'm not sure if it is possible in a order.
Our app is selling a service and we have a case when a required data is available after checkout only.
It depends on the purpose of your customization. Order Item has custom options stored as serialized array and at any time it is possible for your to modify it.
Unlike quote item, in order item it has different name for retrieving them. The method is called getProductOptions()
Also there is another method that allows you to set them setProductOptions(array $options)
.
Here is some examples of this method usage in different test cases:
If you need to store it only for internal code usage, you can just add option into array array and set it back:
$existentOptions = $orderItem->getProductOptions();
$existentOptions['your_custom_option'] = $yourCustomValue;
$orderItem->setProductOptions($existentOptions);
If you need to show your custom option in the printed document, you need to add your custom option into special option of options, that have structure for showing up its value on the frontend, pdf documents, items list
$existentOptions = $orderItem->getProductOptions();
if (!isset($existentOptions['additional_options'])) {
// If special options of options array is set before, create it.
$existentOptions['additional_options'] = array();
}
// Adding visible options value
$existentOptions['additional_options'][] = array(
'label' => 'Your Option Label',
'value' => 'Your Option Value',
// The last one that is optional (if not set, value is used)
'print_value' => 'Your Option Value shown in printed documents'
);
$orderItem->setProductOptions($existentOptions);
Both of these methods even can be combined, if you need one option that is visible to customer and another option that is required for your code.
Also don't forget to save your order/order item after you deed your modifications.
Advice
If you save order and haven't modified the order model itself, you need at least change some data in it, to force order model save all sub entities. For making this possible, you even can just set some non existent attribute.
Case when save operation will not be invoked:
$order->load($id);
$orderItem->getItemById($itemId);
$orderItem->setSomething(111);
$order->save(); // Order Item will not be saved!!
Case when save operation will be invoked:
$order->load($id);
$orderItem->getItemById($itemId);
$orderItem->setSomething(111);
$order->setSomeNonExistentProperty(true);
$order->save(); // Now it will be saved
Have fun with Magento development
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With