I'm trying to calculate the cost of an unsaved line item with a given product and quantity.
I'm using Commerce Discounts as well as Commerce Price Table which changes the price of a product depending on the quantity.
When I run commerce_product_pricing_invoke($line_item), it fires all rules reacting to the Calculating the sell price of a product event including Commerce Price Table and Commerce Discounts. The disconnect I'm seeing however is when commerce_discount_percentage() hits and it attempts to get the unit price...

$unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);

... The line item wrapper already has data in $wrapper->data which prevents it from returning my intended price received from the Price Table module.
I know this happens in entity.wrapper.inc inside the EntityMetadataWrapper class for the value() function which checks if !isset($this->data then getPropertyValue().
However, $this->data IS SET and it is set with the original price of the product instead of the updated Price Table pricing...

public function value(array $options = array()) {
  if (!isset($this->data) && isset($this->info['name'])) {
    $this->data = $this->info['parent']->getPropertyValue($this->info['name'], $this->info);
  return $this->data;

The workaround I've found is to clear the wrapper before calling for the value() in commerce_price_wrapper_value().

function commerce_price_wrapper_value($wrapper, $field_name, $default = FALSE) {
  // Extract the price field's value array from the given entity.
  $wrapper->{$field_name}->clear(); // ADDED THIS.
  $price = $wrapper->{$field_name}->value();

I'm not sure of what the impact of adding $wrapper->{$field_name}->clear(); will be in terms of performance and accuracy of data with so many other functions calling commerce_price_wrapper_value() so I just wanted to point that out and ask if there is something I'm doing wrong?
Here's my code trying to get pricing per quantity (based on the commerce price table) with a discount applied...

$product = commerce_product_load();
foreach ($quantities as $quantity) {
  $line_item = commerce_product_line_item_new($product, $quantity, $order_id);
  $amount = $line_item->commerce_unit_price[LANGUAGE_NONE][0]['amount'];

I appreciate your help and feedback.

Your Answer

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

Browse other questions tagged or ask your own question.