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:
How do I set the alt tag for an existing image field?
$node->save()
)?hook_node_presave
, i think you miss just$node->save()
as @Clive said