Score:1

Can I use Price Resolvers for dynamic product pricing?

us flag

All cart items are adding programmatically. I am trying to set a product cost based on various factors that change for each instance of an item added to the cart.

I discovered Price Resolvers and it seemed like it was working until I ended up adding 2 of the same "dynamically priced" items to my cart. Each was passed different prices and in my resolver I can see that the price is set correctly for each item. However, in the cart, they both have the same cost (the cost of the last item added to the cart).

My guess is that I can only set the price of an item per php session and not per cart item add. Is this correct? Is there some other way to dynamically set price of a product as it is added to a cart?

Score:0
us flag

Eventually sorted this out on my own. Simple answer is NO, this is not the purpose of Price Resolvers. Price Resolvers can be used to "statically" set a price based on something which does not change during the php session - such as location, year, etc. But if you need to modify the price due to user input at the time; the correct solution is to set the Unit Price.

Before looking at Resolvers I already had this code:

  $order_item = OrderItem::create([
    'type' => $item_type,
    'purchased_entity' => $variation->id(),
    'quantity' => isset($options['qty']) ? $options['qty'] : 1,
    'unit_price' => $my_dynamic_price,
  ]);

and I have seen posts and had been given suggestions that this works. It does not. Setting the unit_price at the time of OrderItem::create has no impact on the item's price. The correct way to do this is with the setUnitPrice() method like this:

  $order_item = OrderItem::create([
    'type' => $item_type,
    'purchased_entity' => $variation->id(),
    'quantity' => isset($options['qty']) ? $options['qty'] : 1,
    'unit_price' => $variation->getPrice(),  // may be overwritten by $options['cost']
  ]);

  // If we are setting a custom cost, override unit_price now.
  if (isset($options['cost']) && $options['cost']) {
    $order_item->setUnitPrice($options['cost'], TRUE);;
  }
  $order_item->save();
I sit in a Tesla and translated this thread with Ai:

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.