I want to create multiple nodes using one form, but I'd like to have connection between them stored in Entity Reference, so I need to know their nids. But they aren't created yet, so they hasn't nids.

Question: Is there a way to predict future nodes nids and preserve them for a while or do something similar to deal with task above?


Unfortunately, there's no a clean way to do that!

| improve this answer | |
  • I thought so, but it was worth asking – Gregory Zbinsky Mar 20 '12 at 11:16

Create all nodes with pseudo-random values. Receive all nids. They are reserved now.

After that, within the submit handler, update all node objects.

| improve this answer | |

The nid is available after node_save($node);

You can access is from the same function that does the node_save


global $user;

$entity = array(
  'type' => 'article',
  'title' => 'Example node',
  'uid' => $user->uid,
  'created' => REQUEST_TIME

// Uses Entity API module
$node = entity_create('node', $entity);

// Node object is passed by reference and has nid property after save.

drupal_set_message(t('Node %title nid is %nid', array('%title' => $node->title, '%nid' => $node->nid)));
| improve this answer | |

I had a similiar requirment but I dont know how helpful it will be, Check out this question

You may be able to use $last_id = db_last_insert_id($table, $field);

| improve this answer | |

My idea is to create dummy field with some unique token same for all node types that I need to connect. After submission (creation of multiple nodes) I'll check nodes WHERE token is equal and I'll try to set them Entity relation somehow.

My first thought after getting 'no a clean way to do that' answer.

| improve this answer | |

If you insert a new node say node/71 then next node will always be node/72
NIDs are auto incremented in mysql tables. To get the NID of recently inserted node you can do this query.
SELECT MAX(nid) FROM {node}
You can increment it by 1 to predict next node nid.

| improve this answer | |
  • 1
    No. If a node is deleted in between, the next nid will be 73 while the MAX(nid) will return 71. – jozi Apr 22 '15 at 8:26

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.