by Jeff Eaton

Quick-and-dirty CCK imports

Recently I needed to import a small (100-200) node set from an 'old' database to a CCK content type. I used the following code, which serves as a nice example of the drupal_execute() function.


$results = db_query("SELECT * from recipe");
while ($recipe = db_fetch_object($results)) {

  // I was converting old style nodes to CCK nodes.
  // If you're building them from scratch you would
  // want to use: $node = array('type' => 'story'),
  // where 'story' is the type of node you want to
  // create.
  $node = node_load($recipe->nid);

  $values = array();

  // You'll recognize this as the structure of
  // form_values you'll see in a submit or validate
  // handler. You're basically building it manually,
  // rather than using $_POST from a user.
  $values['field_servings'][0]['value'] = $recipe->yield;
  $values['field_prep_time'][0]['key'] = $recipe->preptime;

  $i = 0;
  $ingredients = db_query("SELECT ingredient FROM
    recipe_ingredients WHERE nid = %d ORDER BY weight ASC",
    $recipe->nid);
  while ($ing = db_fetch_object($ingredients)) {
    $values['field_ingredients'][$i++]['value'] = $ing->ingredient;
  }

  // Multivalue CCK fields are handled this way --
  // the name of the field, then a numerical key for
  // each individual field instance, then a 'value'
  // key. Single-value fields are actually handled
  // the same way, but they only have the '0' delta.
  $values['field_directions'][0]['value'] = $recipe->instructions;
  $values['body'] = $recipe->notes;
  $values['field_source'][0]['value'] = $recipe->source;
  $values['status'] = 1;
  //$values['promote'] = 1;

  // 'recipe_node_form' would be 'story_node_form' or
  // whatever node type you're creating.
  drupal_execute('recipe_node_form', $values, $node);
}
?>
newsletter-bot