Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
What if field name is unknown (field_images)
hello I am making a web services module
and have something like this
Than way later I have
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
It should be something like
It should be something like following code.
There can be some TYPO but it would work something like this.
Pushpinder Rana #pushpinderdrupal
Acquia Certified Drupal Expert