1

When using entity wrapper to modify and save an entity, what is the preferred way of accessing the updated entity.

For example, after the following code saves the node:

$node = node_load(123);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

After that, what is the preferred way to access the updated node object (the full object, not just field values)?
Can it be accessed via the wrapper in some way or do you have to load the node again?

1 Answer 1

3

There's no "preferred" way, as such, but I guess if you're using the wrapper to work with the entity, it makes sense to stick with that convention to re-access it.

Don't forget you've just altered an in-memory object, so regardless of the persistence layer, that object will still have the changes in it.

Once you've done this:

$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

Your changes will immediately be available by inspecting

$node_wrapper->field_textfield

EMWs use the core entity API under the hood, so persistence is actually done through the default entity controller. As such, everything that would happen in calling node_save(), for example, happens when you update the wrapper object.

In practical terms, that means you can save an entity with EMW, and also access the changes on it immediately using an object returned from entity_load(). It's the same underlying object in memory.

I think it's safe to say that context, and even surrounding code/conventions, will often dictate the particular method you use.

4
  • Ah, so you can just use the existing $node variable to access the whole entity. That's what I thought and it turns out I had another issue going on that was causing me unexpected behaviour and confusion.
    – rooby
    Sep 29, 2015 at 9:57
  • Yeah objects (like nodes etc) are essentially pass-by-reference in PHP, so anything that affects them in one context automatically affects them in all other contexts. An EMW is just an OO wrapper around the node object underneath, and the original $node that you've loaded will contain the changes, so it almost doesn't matter which method you use to access it, apart from from a standards point of view
    – Clive
    Sep 29, 2015 at 9:59
  • So is $node_wrapper->value() the equivalent "node wrapper" way of accessing $node?
    – rooby
    Sep 29, 2015 at 10:05
  • Yep, $node_wrapper->raw() will also get you the same thing I think
    – Clive
    Sep 29, 2015 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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