Score:0

Setting $order_item->setUnitPrice($price, TRUE);) stops cart items being merged, how to prevent this?

cn flag

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();
}
No Sssweat avatar
ua flag
Let me see the whole picture. Can you post the entire code that gets runned on the `CART_ENTITY_ADD` event?
thiokol avatar
cn flag
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?
Score:0
ua flag

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.

thiokol avatar
cn flag
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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.