1

I'm trying to do a mass import of images to drupal nodes in D7 and ended up with lots of funny entries in the table {files_managed}.

This is the code I use:

  chdir('/path/to/drupal/root');
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $node = node_load(123);

  $dir = '/path/to/files';
  if ($handle = opendir($dir)) {

    while (false !== ($file = readdir($handle))) {
      $file_ext = pathinfo($file, PATHINFO_EXTENSION);

      switch ($file_ext) {
        case 'jpg':
        case 'gif':
        case 'JPEG':
        case 'jpeg':
        case 'png':
          $name_explode = explode("_", $file);
          $image_location =  $dir .'/'. $file;

          $file_temp = file_get_contents($image_location);
          $file_temp = file_save_data($file_temp, 'public://' . $file, FILE_EXISTS_RENAME);
          $node->field_ep_image = array(
            $node->language => array(
              0 => array(
              'fid' => $file_temp->fid,
              'filename' => $file_temp->filename,
              'filemime' => $file_temp->filemime,
              'uid' => 1,
              'uri' => $file_temp->uri,
              'status' => 1
              )
            )
          );
        break;
      }

    }

    closedir($handle);
  }

What is the correct way to populate an imagefield programmatically in D7?

2

You only need to store the fid on the node, the rest of the file data is stored in the files table.

So

$node->field_ep_image = array(
   $node->language => array(
     0 => array(
       'fid' => $file_temp->fid,
     )
   )
 );

should be fine.

You could also use the entity API module, which simplifies this for you:

$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_ep_image = $file_temp->fid;

If you are getting funny values you might want to check your file handling, are the files save in the files table as expected?

1
  • Hey googletorp, that's very good pointers there, especially for the new entity API. Didn't know I can do it like that. As for the files table, to be precise, did you mean 'files_managed' table?
    – Logi
    Jul 20 '11 at 15:45
2

I don't have the exact answer to your question, but you could check how other modules do it. Devel Generate for instance (part of Devel) can populate image fields. Check out devel_generate_fields() in devel_generate.fields.inc and image_devel_generate() in image.devel_generate.inc.

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.