- Issue created by @hamza_niazi
- 🇵🇰Pakistan hamza_niazi
The alt text is skipped in media image when uploading through bulk upload and in manage display format is selected as thumbnail but it works fine we change the format to render entity than it works fine
- 🇵🇰Pakistan hamza_niazi
So far what i have done is in my custom module using form alter hook
**
* Implements hook_form_alter().
*/
function custom_module_form_alter(&$form, FormStateInterface $form_state) {
if ($form_state->getFormObject() instanceof \Drupal\media\MediaForm) {
$form['actions']['submit']['#submit'][] = 'custom_module_process_alt_text';
}
}/**
* Custom submit handler to set alt text for media images and thumbnails.
*/
function custom_module_process_alt_text(array &$form, FormStateInterface $form_state) {
$media = $form_state->getFormObject()->getEntity();
if ($media->hasField('field_media_image')) {
$current_alt_text = $media->get('field_media_image')->first()->get('alt')->getValue();
if (!empty($current_alt_text)) {
$reflection = new \ReflectionClass($media);
try {
$method = $reflection->getMethod('updateThumbnail');
$method->setAccessible(true);
$thumbnail_field = $media->get('thumbnail');
if ($thumbnail_field) {
$thumbnail_field->alt = $current_alt_text;
}
$method->invoke($media);
}
catch (\ReflectionException $e) {
\Drupal::logger('simple_media_bulk_upload')->error('Error updating thumbnail alt text: @message', [
'@message' => $e->getMessage(),
]);
}
$media->save();
}
}
}
this code is useful when in manage display you are using format as thumbnail i have done this way - 🇵🇰Pakistan hamza_niazi
I have came with this alternative solution if you have have existing thumbnails images and you want to add to alt text to existing images
then i have done that by doing thisfunction custom_module_entity_load(array &$entities, $entity_type) { if ($entity_type === 'media') { foreach ($entities as $media) { if ($media->hasField('field_media_image') && !$media->get('field_media_image')->isEmpty()) { $media_image_field = $media->get('field_media_image'); $alt_text = $media_image_field->first()->get('alt')->getValue(); $media_target_id = $media_image_field->first()->get('target_id')->getValue(); if ($media->hasField('thumbnail') && !$media->get('thumbnail')->isEmpty()) { $thumbnail_field = $media->get('thumbnail'); $thumbnail_item = $thumbnail_field->first(); if ($media_target_id === $thumbnail_item->get('target_id')->getValue()) { $thumbnail_item->set('alt', $alt_text); } } } } } }