4

I am implementing hook_commerce_cart_line_item_refresh(). It will be receiving line item and entity metadata wrapper for the commerce order.

How can I get user id of order from its metadata wrapper without loading user object like this

$uid = $order_wrapper->owner->value()->uid

With above line it will be loading user object. I would like to avoid loading user object and simply take uid directly.

Following line does not work:

$uid = $order_wrapper->uid;

Or should I think of loading order object? As it might be already in static cache.

Thanks

8

It's the same as any property on a metadata wrapper:

$uid = $order_wrapper->uid->value();

Or should I think of loading order object?

You can't have an entity metadata wrapper without an underlying entity, so the object you're referring to is already 'loaded'. You can get it with

$order = $order_wrapper->value();
  • Oh, why didn't I try that simple line!! – Junaid Sep 25 '14 at 9:46
  • This is not correct, check 3rd answer, $uid = $order_wrapper->author->uid->value(); – Ponzio Pilato Feb 28 '17 at 18:28
  • The order entity has a uid property @Ponzio - it's correct. Your method is identical to this, except it involves unnecessary database calls – Clive Feb 28 '17 at 18:32
2

You need to get uid from the entity object.

$uid = $order_wrapper->value()->uid;
0

For a multi-valued entity reference field you can get the raw values using this pattern

$wrapper->field_multiple->raw()

This would return an array like this:

array(0 => 123, 1 => 456)
-1

Correct answer is:

$uid = $order_wrapper->author->uid->value();

  • 1
    This isn't right - see commerce_order_entity_property_info(). The related user entity is available through the owner property, not author. This code might work for a node, or for a custom property you or something else has defined on commerce_order, but would be equally redundant as using $order_wrapper->owner->uid->value(), forcing a load of the user object just to get an ID you already have in $order_wrapper->uid->value() – Clive Feb 28 '17 at 18:40

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.