Skip to main content
1 of 7
Rob
  • 341
  • 2
  • 14

No "body" when creating a node programatically

I am trying to create event type nodes, using data from an external database. It's reading correctly, and creating a node almost perfectly. But, it doesn't seem to save the "body" part of the node.

db_set_active('default');

foreach ($results as $record) { // Results gained from an ext DB
  echo 'Creating event: ' . $record->name;

  $node = new stdClass();
  $node->type = 'event';
  node_object_prepare($node);

  $node->title    = $record->name;
  $node->language = "en";;

  $node->body[$node->language][0]['value']   = $record->bodytext;  /* This line ?? */

  $path = 'content/programmatically_created_node_' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);  
}

This is early stages, and I have a number of fields to put into events type nodes, including some custom fields.

I am unsure how to map the fields in the external database to node fields. The line above might be completely wrong at this stage, but it's gone though many many failing iterations.

===

I also tried using the drupal_form_submit method..

foreach ($results as $record) { // Results gained from an ext DB
    echo 'Creating event: ' . $record->name;
    $node = (object) array(
      'type' => 'event',
      'language' => LANGUAGE_NONE
    );
    node_object_prepare($node);

    $form_state = array();  
    $form_state['values']['language'] = "en";
    $form_state['values']['title'] = $record->name;  
    $form_state['values']['description']['value'] = "description....";
    $form_state['values']['body']['value'] = "body....";
    $form_state['values']['body']['format'] = filter_default_format();
    $form_state['values']['body']['LANGUAGE'] = "en";
    $form_state['values']['name'] = $user->name;  
    $form_state['values']['op'] = t('Save');

    drupal_form_submit("{$node->type}_node_form", $form_state, $node);

}

But again, try as I might, using this method I could not get the "body" to be saved. (I know there is some junk in this code, it's my experimentation.)

Questions.

  1. Which is the best method to use for my application. node_save or drupal_form_submit
  2. For the correct method, which is the best way to store the body text?
  3. How do I know what are valid $form_state array keys, or $node elements, so I can find the correct place for further field mapping?
Rob
  • 341
  • 2
  • 14