Thursday 11 July 2013

Create a node programmatically in drupal 7 with Reference fields

How to create the node programmatically in drupal 7 with Reference field modules either References or Entity Reference(that is in drupal 8 core now).

Also find the below example of creating a simple node with page type with Title,Description and a Reference(References or Entity Reference) fields.
$node = new stdClass();
$node->uid = 1;
$node->title = 'Title of the Field';
$node->status = 1;
$node->comment = 1; //Hidden the Comment on the node
$node->promote = 1;
$node->sticky = 0;
$node->type = 'article';
$node->created = '';
$node->changed = '';
$node->timestamp = '';
$node->body['und'][0]['value'] = 'Full Story';
$node->body['und'][0]['summary'] = 'Summary';
$node->body['und'][0]['format'] = 'full_html';
$node->revision = 0;
$node->field_entity_reference['und'][0]['target_id'] = 50;
//Here field_entity_reference is the name of the Entity Reference Field and 50 is the nid of the reference node.
$nid = node_save($node);
Here field_entity_reference is the name of the Entity Reference Field and 50 is the nid of the reference node.
you will get the $nid after saving the node

3 comments :

  1. Really Helpful saves my lot of time.Thanks for posting

    ReplyDelete
  2. This Script Is really Helpful Please Can You tell Me My Drupal Is not Working in Wimapp...
    Best Web Design

    ReplyDelete
    Replies
    1. I think this script can't break your drupal working.
      Please let me know did this script cause problem.

      Delete