0

So I have an entity called "Discount" with the following fields:

  • field_discount_percentage is an integer field.
  • field_discount_price is a commerce price field.

I can test whether the percentage field contains a value to avoid exceptions via:

if (empty($discount_wrapper->field_discount_percentage))

However this does not work for commerce price fields, as $discount_wrapper->field_discount_price is an object in itself and so the following is always true:

if (empty($discount_wrapper->field_discount_price))

Alternatively I tried:

if (empty($discount_wrapper->field_discount_price->amount))

However this produces an exception on zero values, and the following:

if (empty($discount_wrapper->field_discount_price->value()))

Which returns a PHP Fatal error as empty() can only take variables and not functions.

I am now resorting to:

if ($discount_wrapper->field_discount_price->value())

However this does not feel explicit and I was hoping there is a more conventional means to test price fields.

0

Adding isset() to that last if statement is a bit more explicit.

if (isset($discount_wrapper->field_discount_price->value()))
| improve this answer | |
  • That won't work as the call happens before isset, so you'll get an error anyways if the field is not existant. – pcambra Jul 11 '14 at 17:11
0

Not sure what you're looking for but you've got commerce_price_wrapper_value function to extract a price from an entity in a consistent way, example:

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

The third parameter is a boolean that indicates to return the default price structure.

| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.