10

This question already has an answer here:

I need to pull the nid immediately after it is created using entity_metadata_wrapper as a creation method.

Here is a brief example:

$values = array(
  'type' => 'content_type',
  'uid' => $user->uid,
  'status' => 1,
  'comment' => 1,
  'promote' => 0,
);

$entity = entity_create('node', $values);
$wrapper = entity_metadata_wrapper('node', $entity);
$wrapper->title->set('title');
$wrapper->save(true);
entity_save('node', $entity); 

// From this, where can I get a NID value for the node that was just created?

marked as duplicate by mpdonadio Oct 1 '13 at 21:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • If you have devel module installed than can you check what does this returns: dpm($wrapper);. Otherwise try the following code: echo '<PRE>'; print_r($wrapper); echo '</PRE>'; – Ankit Agrawal Oct 1 '13 at 20:11
  • 2
    Just a note, but you don't need $wrapper->save() and entity_save() - just one will suffice, else you're saving the node twice. Also, nid will be added to the wrapper after save, e.g $wrapper->nid->value(); – David Thomas Oct 1 '13 at 20:58
27

You can simply use the entity_metadata_wrapper's integrated method to get the ID:

$wrapper->getIdentifier()
6

Easy.

 $wrapper->save();
 $node = $wrapper->value();
 dsm($node); // which has $node->nid;

Figured I'd answer for somebody else to use.

Update:

The answer above is a better answer $wrapper->getIdentifier().

There are situations when the entity may have some sort of unique identifier.

  • 2
    The next answer show the right ways to do this stuff. $wrapper->getIdentifier() – mouhammed Oct 22 '14 at 17:06
  • Thanks, and you're right. I've updated my answer to reflect it as so :) – inertialmedia Jan 19 '15 at 5:27

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