1

I would like to update a custom field, added to my order items, in the price resolver process. The price resolver process do some sort of queries to select the right price and this selection has a key that I want to save in the custom field. I'm not sure how could I alter the order line item after the right price was selected.

2
  • How are you doing the price resolver? Custom code or contrib module?
    – No Sssweat
    Oct 5 '20 at 9:48
  • With a custom module. In "resolve" function I calculate de new price and return the new object.
    – briast
    Oct 5 '20 at 10:47
2

You price resolver should have something like

if (isset($result['price'])) {
    return new Price((string) $result['price'], $context->getStore()->getDefaultCurrencyCode());
}

Before your price resolver's return line put:

$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
$order_items = $cart->order_items->referencedEntities();
foreach ($order_items as $order_item) { 
  if (!empty($order_item->field_custom)) {
    $order_item->field_custom->value = 'Hello World'; // set new value
    $cart_manager = \Drupal::service('commerce_cart.cart_manager');
    $cart_manager->updateOrderItem($cart, $order_item);
  }
}
1
  • Thanks for your answer. It works like a charm.
    – briast
    Oct 6 '20 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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