29 November 2015

Changing line item price is not as easy as you could think. It can seem that the price has changed, but there are multiple places where you have to actually change it. Especially when you compute the price from your module(not using rules), because of more complicated logic.

Source code viewer
  1. /**
  2.  * Implements hook_commerce_product_calculate_sell_price_line_item_alter().
  3.  *
  4.  * Alter the price in list and single product page.
  5.  */
  6. function HOOK_commerce_product_calculate_sell_price_line_item_alter($line_item) {
  7. global $user;
  8.  
  9. $user_wrapper = entity_metadata_wrapper('user', $user->uid);
  10. $product_wrapper = entity_metadata_wrapper('commerce_product', $line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
  11. $price_formulas = $product_wrapper->field_price_formulas->value();
  12. $prices = $product_wrapper->field_prices->value();
  13. $price_formula = $user_wrapper->field_customer_price->value();
  14.  
  15. if ($key = array_search($price_formula, $price_formulas)) {
  16. // Assign new price to the line item.
  17. $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount'] = $prices[$key] * 100;
  18. }
  19.  
  20. }
  21.  
  22. /**
  23.  * Implements hook_commerce_cart_line_item_refresh().
  24.  *
  25.  * Alter the price in cart and order.
  26.  */
  27. function HOOK_commerce_cart_line_item_refresh($line_item, $order_wrapper) {
  28. global $user;
  29.  
  30. $user_wrapper = entity_metadata_wrapper('user', $user->uid);
  31. $product_wrapper = entity_metadata_wrapper('commerce_product', $line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
  32. $price_formulas = $product_wrapper->field_price_formulas->value();
  33. $prices = $product_wrapper->field_prices->value();
  34. $price_formula = $user_wrapper->field_customer_price->value();
  35.  
  36. if ($key = array_search($price_formula, $price_formulas)) {
  37. $price = $prices[$key] * 100;
  38. // Assign new price to the line item and line item base.
  39. $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount'] = $price;
  40. $line_item->commerce_unit_price[LANGUAGE_NONE][0]['data']['components'][0]['price']['amount'] = $price;
  41. }
  42. }
  43.  
Programming Language: PHP