Drupal node_save

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


Drupal node_save is the API available in Drupal 4-7 that must be used to insert or save a node. This API function can be called anywhere in the module or theme file like template.php and is available from the core.

An example usage can be seen in the example below:

<?php

 $edit 
= array();
  
$edit['type'] = 'blog'//type of the blog

  
$edit['uid'] = $user->uid;// user who would be called the  creator of the node

  
$edit['promote'] = 1;
  
  
$edit['format'] = FILTER_FORMAT_DEFAULT;
  
$edit['status'] = 1;

    
$edit['title'] = 'Title of the node';
    
$edit['body'] = 'Description of the node';

  
node_validate($edit);
  
$node node_submit($edit);
  
node_save($node);

?>

Above code would save a new entry with title "Title of the node" of type 'blog'.

You can similarly update an existing node using drupal node_save as follows:

<?php
$node 
node_load($nodeid);
$node->title "Updated title";
  
node_validate($edit);
  
$node node_submit($edit);
  
node_save($node);

?>

You would notice couple of other related APIs above: node_load, node_validate and node_submit before actually doing node_save. Drupal node_load loads a node object from the database. Drupal node_validate performs validation checks on the given node. Drupal node_submit Prepare node for save (drupal node_save) and allow modules to make changes.

Some related details on node_save drupal can be had from the link.





-1 points

In your second example, you use $edit without defining it. Should this be $node where you are using $edit?

<?php
$node 
node_load($nodeid);
$node->title "Updated title";
  
node_validate($node);
  
$node node_submit($node);
  
node_save($node);

?>

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.