[Drupal] How to save a node programmatically?

| | 2 min read

In Drupal, all content is stored and treated as "nodes" - an abstraction to process data. A node is any posting, such as a page, article, or blog entry. Comments are not stored as nodes but are always tied to one. Treating all content as nodes allows the flexibility of creating new types of content. It also allows you to effortlessly apply new features or changes to content.Read on to know how to save node programmatically

By default, Drupal provides two different content types called Article and Basic page. We can create numerous content types using the Drupal user interface. These two content types are stored as nodes for easy manipulation. Nodes can also be created programmatically. Take a look at the code below. The code is self-explanatory. (All code should be placed in your very own custom Drupal module)

  
    $node = new stdClass();
    // It defines the type of the object
    // It should be exactly same as content type name(machine name in Drupal)
    $node->type = 'machine name of the particular content type';
    // It should be exactly same as content type name(machine name in Drupal) 
    // The title which we mentioned in our site.
    $node->title = "Value of particular field"($form_state['values']['email']);
    // As same as field names i.e machine name for every fields.
    $node->field_name['und'][0]['value'] = $form_state['values']['name'];
    $node->field_phone_number['und'][0]['value'] = $form_state['values']['phone'];
    $node->field_date_of_birth['und'][0]['value'] = "{$form_state['values']['dob']['year']}-{$form_state['values']['dob']['month']}-{$form_state['values']['dob']['day']}"; 
    $node->language = 'und';
    $node->status = 1; // published defines 1.
    $node->uid = $user->uid; // users id from default user variable.
    node_save($node); // To create a node.
  

In the above code, the $node->title, $node->field_name, $node->field_phone_number, $node->field_date_of_birth explains the field's machine as like which we added in content type in coding. The fields I have posted here are just examples. It may be changed according to the field that you created