0

Drupal Commerce 2, with Drupal 9.

In the CART_ENTITY_ADD event, if i set $order_item->setUnitPrice($price, TRUE); identical items added to the cart get added as new order items, but I want them to be merged.

If I comment out this line in my code the items get merged as expected and their quantity is summed.

How do i set the unit price without the order items being treated as distinct order items?

Relevant code of the CART_ENTITY_ADD event:

public function addToCart(CartEntityAddEvent $event) {
    $order_item = $event->getOrderItem();
    // update order item
    $order_item->setUnitPrice($price, TRUE);
    $order_item->save();
}
2
  • Let me see the whole picture. Can you post the entire code that gets runned on the CART_ENTITY_ADD event?
    – No Sssweat
    Jan 22, 2022 at 3:46
  • Hey @No Sssweat - I've updated my question with the full code. I don't think most of the code is relevant to the issue, as when I remove the $order_item->setUnitPrice($price, TRUE); line it works as expected and the items and quantities are merged. I think the Commerce OrderItemMatcher must not want to merge items when the unit price is set like this? Jan 22, 2022 at 10:53

1 Answer 1

0

Hmmmmmmm rather than order_item->save();, try using the cart manager

// get the cart
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
// update the cart
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$order_item->setUnitPrice($price, TRUE);
$cart_manager->updateOrderItem($cart, $order_item);

Bonus: Some methods/functions you might find useful.

1
  • 1
    Thanks for the reply. I actually ended up moving the pricing logic into a price resolver instead. Thats probably where it should belong anyway. Everything works properly when the pricing logic is moved out of the CART_ENTITY_ADD event and into the price resolver. Jan 25, 2022 at 12:02

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.