1

I have a Drupal 8 site with a content type that has an image field. For existing nodes of this type, most have image files, but none have alt tags.

I am writing an update hook where I want to set the alt tag value for existing nodes. However, I have not been able to figure out how, nor find documentation.

This is what I have:

$nids = \Drupal::entityQuery('node')->condition('type','sfa_social_post')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ( $nodes as $node ) {
  $node->field_sfa_image_file->alt = 'Image for ' . $node->getTitle();
}

Where field_sfa_image_file is the name of the image field.

When I re-loop through the nodes, I get back the value that I set.

$nids = \Drupal::entityQuery('node')->condition('type','sfa_social_post')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ( $nodes as $node ) {
  drush_print('Title: ' . $node->getTitle());
  drush_print('Alt: ' . $node->field_sfa_image_file->alt);
}

Which gives me

Title: Instagram Post ID: 1917569620391415985_3017827348
Alt: Image for Instagram Post ID: 1917569620391415985_3017827348
Title: Instagram Post ID: 1917562614863492125_3017827348
Alt: Image for Instagram Post ID: 1917562614863492125_3017827348

So all seems good. However, when I navigate to nodes, I don't see my alt text:

enter image description here

How do I set the alt tag for an existing image field?

  • 1
    Have you saved the nodes ($node->save())? – Clive Jan 8 at 21:56
  • ` $node->field_image->alt = 'some alt';` works for me, i have tested it in hook_node_presave, i think you miss just $node->save() as @Clive said – berramou Jan 8 at 22:28
3

As @clive suggested use $node->save();. Without node saving, alt of the image will not show up in the edit form.

$nids = \Drupal::entityQuery('node')->condition('type','sfa_social_post')->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
foreach ($nodes as $node) {
  $node->field_sfa_image_file->alt = 'Image for ' . $node->getTitle();
  $node->save();
}

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.