Sometimes you have requirement to attach existing images with some existing node. Now there is two either you upload images manually for each node or create a small snippet that do this work for you. So here is a small snippet that do the similar thing with less code, you can easily iterate this for multiple load also.

In this example I am associating multiple existing images with one node i.e nid is 2.


/*
 * Programmatically attach existing images with existing node image field that
 * configured for 'multiple values'.
 */

$nid = 2;
$target_images = array(12, 13, 14, 15, 16);
$node = node_load($nid);
$images_fid = db_query("SELECT fid FROM {file_usage} WHERE id IN (:images_nid)", array(":images_nid" => $target_images));
if ($images_fid->rowCount() > 0) {
  foreach ($images_fid as $image_fid) {
    $file = file_load($image_fid);
    if (isset($file->filename)) {
      file_usage_add($file, 'file', 'node', $node->nid); // Don't forget to add this line.
      $node->field_images[LANGUAGE_NONE][] = array(
          'fid' => $file->fid,
          'filename' => $file->filename,
          'filemime' => $file->filemime,
          'uid' => 1,
          'uri' => $file->uri,
          'status' => 1
      );
    }
  }
}
node_save($node);

Comments

taggartj’s picture

hello I am making a web services module

and have something like this

//check for user has set custom machine  image field  suchas $field field_mytestimage
if(!isset($field)){
  	//defaults to normal article field_image
  	$field ="field_image";
  }

Than way later I have

$node = node_load($nid);

$node->field_image[LANGUAGE_NONE][] = array(
  'fid' => $fid, // is known 
  'display' => 1,
  'description' => '',
	);
	
node_save($node);

now the question is how in the heck do you do something like the following

$node->'what_ever_the_user_hasset_as_a_custom_field'[LANGUAGE_NONE][] = array(
or to explain
$node->'.$field.'[LANGUAGE_NONE][] = array(

Just trying to make a module that takes in to account an unkown file field

er.pushpinderrana’s picture

It should be something like following code.

$custom_field = 'field_mytestimage';
$node->{$custom_field}[LANGUAGE_NONE][] = array(
          'fid' => $file->fid,
          'filename' => $file->filename,
          'filemime' => $file->filemime,
          'uid' => 1,
          'uri' => $file->uri,
          'status' => 1
      );

There can be some TYPO but it would work something like this.

Pushpinder Rana #pushpinderdrupal
Acquia Certified Drupal Expert