10

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?
2
  • 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>'; Commented Oct 1, 2013 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(); Commented Oct 1, 2013 at 20:58

2 Answers 2

28

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
  • 2
    The next answer show the right ways to do this stuff. $wrapper->getIdentifier()
    – mouhammed
    Commented Oct 22, 2014 at 17:06
  • Thanks, and you're right. I've updated my answer to reflect it as so :) Commented Jan 19, 2015 at 5:27

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