Drupal Nodes

Creating a node programmatically

In this code example, we are creating a new node of the type "listing_claim". The function "claim_listing_save" is being called from callback function inside a custom module that processes a Drupal form.

function claim_listing_save($data) {
    //$data is data submitted by a drupal form
    $company =  $data['companyname'];
    $name = $data['name'];
    $customMessage = $data['customMessage'];
    $listingTitle = $data['thisTitle'];
    // Let's save the Claim node
    $node = new stdClass();
    node_object_prepare($node);
    // set the node type
    $node->type = 'listing_claim';
    // prepare the body text
    $body_text = $customMessage;
    // set the node title, concatenate custom text and variable
    $node->title = "Claim: ".$listingTitle." by ".$name;
    $node->language = LANGUAGE_NONE;
   // set the body text
    $node->body[$node->language][0]['value'] = $body_text;
    // save the node
    node_save($node);
    // get the id of the new node
    $nid = $node->nid;
    // return the nid
    return $nid;
}