Skip to content

Instantly share code, notes, and snippets.

@iamstoick
Last active September 8, 2017 06:05
Show Gist options
  • Save iamstoick/8c36c46b7cdfab37456ad18fdb7b81c1 to your computer and use it in GitHub Desktop.
Save iamstoick/8c36c46b7cdfab37456ad18fdb7b81c1 to your computer and use it in GitHub Desktop.
Get the entity id after saving it programmatically.

Suppose you have a code like this.

$node = entity_create('node', array('type' => 'info'));
$entity = entity_metadata_wrapper('node',  $node);

// Node title.
$entity->title = $info->name;

// Address.
$entity->field_info_address->thoroughfare = $info->address;
$entity->field_info_address->locality = $info->city;
$entity->field_info_address->administrative_area = $info->state;
$entity->field_info_address->postal_code = $info->postalcode;
$entity->field_info_address->country = $info->country;

// Save the entity.
$entity->save();

Now for some reason you have to obtain the node id of the entity. You have two options:

Option 1:

$entity->save();
// Get the entity id.
$nid = $entity->nid->value();

Option 2 (Recommended way):

$entity->save();
// Get the entity id.
$nid = $entity->getIdentifier();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment