0

I am not sure what is the benefit of using system_retrieve_file mentioned on Save image from URL to a field from a custom module, so I just use the following simple code to save image programmatically:

    $file = file_save_data(file_get_contents($url), file_default_scheme().'://field/image/'.basename($url));
    $file->status = 1;
    $node->field_image['und'][0] = (array)$file;
    node_save($node);

Works fine, so now I am trying to figure out how to save the enabled alt value which is stored in $alt variable.

When I output what the $file array contains with dsm(print_r($file,true)); it shows only:

stdClass Object
(
[fid] => 9
[uri] => public://field/image/150304192032_monalisa_624x351_afp_0.jpg
[filename] => 150304192032_monalisa_624x351_afp.jpg
[filemime] => image/jpeg
[uid] => 1
[status] => 1
[timestamp] => 1425596902
[filesize] => 28642
)

Unfortunately, it doesn't contain neither title or alt. Could anyone help me to get this sorted out? Thanks!

1

As far as Drupal 8 is concerned, there is another solution :

//    $file : my File Entity
//    $node : my (Node) Entity having an Image File field associated
$node->field_my_image_field[] = [
 'target_id' => $file->id(),
 'alt' => 'Alt. text',
];
$node->save();

Well, I think that 'width', 'height' and 'title' are also available in the setting array (but target_id seems required). cf: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldType%21ImageItem.php/class/ImageItem/8.2.x (look at the source code, generateSampleValue() method).

0

Ok, I've got this done by using the following code after node_save():

$update = db_update('field_data_field_image')
  ->fields(array(
    'field_image_alt' => $alt,
  ))
  ->condition('field_image_fid', $file->fid)
  ->execute();

It seems this is the only way. More detailed findings are given on https://www.drupal.org/node/2447091

  • This is not the only way. See answer by @A. Lasserre. You should try to use the entity operations, if possible, rather than updating db tables directly. – sonfd Apr 30 at 13:29

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.