Darren Mothersele

Software Developer

Warning: You are viewing old, legacy content. Kept for posterity. Information is out of date. Code samples probably don't work. My opinions have probably changed. Browse at your own risk.

Programmatically Creating CCK Nodes and Adding Images with Imagefield

Apr 23, 2008

web-dev

There's a useful post on civicactions that explains how to create nodes in your Drupal site programmatically. I'm using this technique to create an import script for processing bulk quantities of XML files.

There's a facet to the create node process, in that I couldn't get it to import images using the $values[] array.

I found that I could create all the CCK fields by assigning them fields in the $value[] array, but for imagefield values I had to instantiate them in the $node object instead.

Here's my code for importing imagefields, taken from the XML/JPEG import script:

<?php
  $node
->type = 'album';
 
$node->field_cover_image = array(
    array(
     
'fid' => 'upload',
     
'title' => (string)$xml->album->album_title,
     
'filename' => $img_file->filename,
     
'filepath' => $img_file->filepath,
     
'filesize' => $img_file->filesize,
    ),
  );
 
$values = array();
 
$values['field_album_upc'][0]['value'] = (string)$xml->album->album_upc;
 
$values['title'] = (string)$xml->album->album_title;
 
$values[...] = ...; // rest of CCK fields created here
 
drupal_execute('album_node_form', $values, $node);
?>

Update:

As requested in the comments, here is an import with images working in Drupal 6. This is the code I am using, I'm not sure it's the 100% best recommended way of doing this, but it works for me and it may assist you:

<?php
$imageFile
= $originalPath . $imageFilename;
$original_path = $imageFile;
$imageFile = file_directory_path() .'/images/'. $imageFilename;
if (!
file_copy($original_path, $imageFile)) {
// check file can be copied
return FALSE;
}
$fileUp = array(
'title' => $data['title'],
'filename' => basename($imageFile),
'destination' => $imageFile,
'filepath' => $imageFile,
'filemime' => 'image/jpeg',
'filesize' => filesize($imageFile),
'source' => 'field_cover_0',
'uid' => $user->uid,
);
$node['field_cover'] = array($fileUp);
$node = node_submit($node);
$fileSaved = drupal_write_record('files', $fileUp);
?>