1

I am writing an Android app which is creating Drupal nodes remotely. I am creating these nodes via a straight php form. But now I need to create Nodes which are node_references of the main node. Usually in order to do this you will need the entity ID of the main node before you can create a node reference.

Creating the second node as a reference should be easy as it is just an extra field with a reference value in it. The problem is, once the App creates the main node, I need the entity ID to be returned to the App so that the value can be used to create the other referenced node.

How do I get the entity ID back as a return value after node creation?

or... am I thinking about this all wrong :)

0

If you are using the entity api to create and save your entity its fairly easy:

// Create the node and wrap it in entity metadata wrapper
$node_create = entity_create('node', array('type' => 'my_content_type'):
$node_wrapper = entity_metadata_wrapper('node', $node_create);

$node_wrapper->title->value("My Title"); // Set the title
$node_wrapper->save(); // Node is now saved
$node_nid = $node_wrapper->getIdentifier(); // We now have the nid

// Doing the same thing here except adding the reference
$node_create2 = entity_create('node', array('type' => 'my_other_content_type'):
$node_wrapper2 = entity_metadata_wrapper('node', $node_create2);

$node_wrapper2->title->value("My referenced title");
$node_wrapper2->field_node_reference->value($node_nid);

$node_wrapper2->save();
  • looks great. I had no idea that getIdentifier existed. sure would have been nice for other projects. Thanks – Cybergei Aug 4 '14 at 6:50
  • NP. I always try to use entity api for CRUD operations on any entities. The other option is to use a hook_node_insert which in my opinion is not efficient and would involve creating other nodes after the insert. – chadpeppers Aug 4 '14 at 14:29
  • 1
    nah when sending from a mobile device to the Drupal server, I try to keep it as simply as possible. Thanks for the help guy – Cybergei Aug 4 '14 at 16:15

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.