Using node_save in drupal 7 with CCK fields

 
 
 
Printer-friendly version

If you are a Drupal developer, you probably know how to save a node using node_save() function. I am coming across saving node with CCK fields so often. I had no any issue while on the D6. First time on the Drupal 7, it hurt me lot leaving CCK field blank when saving where I used the same technique as D6. It might help some one of you…

Drupal 6 way of saving CCK

$node = new stdClass(); $node->type = 'application'; 
$node->title = $data["reference"]; 
$node->body = $data['summary']; 
$node->field_ja_first_name[0]['value'] = $data["f_name"]; 
$node->field_ja_middle_name[0]['value'] = $data["m_name"]; 
// etc.. 
node_save ($node);

This steps works fine for Drupal 6.

The Drupal 7 version of above script is follow..

$node = new stdClass(); 
$node->type = 'application'; 
$node->title = $data["reference"]; 
$node->body = $data['summary']; 
$node->field_ja_first_name['und'][0]['value'] = $data["f_name"]; 
$node->field_ja_middle_name['und'][0]['value'] = $data["m_name"]; 
// etc.. 
node_save ($node);

If you look at the code, you will find a new array key “und”. Drupal 7 need this to save the custom fields. So what the heck is this “und”. do not jump to google search. This is just language code only..

Comments

Better to use the defined term LANGUAGE_NONE as it makes it obvious it is a language thing.

ofcourse, we can use that simply.

Add new comment