First off, this is an AWESOME module. If I had found it weeks ago, it would have saved me days of struggles. Thank you!!
Problem/Motivation
I have a Drupal 9 site that has English and French translated nodes using an image field. The alt and title text is translated, but the image is the same for both languages. When using this module to convert the images to media entities, only one language is converted - usually the French - so I ended up with the images in Media, but all with French alt and title text.
I initially thought the SHA1 hashing was triggering and skipping the duplicate image, so I commented out all that in image_field_to_media.batch.inc
, but same result. In the end I did a nasty hack where I forced it to loop through the two languages when loading the image in the batch process. I'm sure there is a nice generic solution, but I can't figure it out.
My nasty hack (in image_field_to_media.batch.inc). I don't recommend this, but I've been fighting this migration (D6 to D9) for ages now and I just want to be done with it:
$entity_id = reset($entity_id);
$entity = \Drupal::entityTypeManager()->getStorage($entity_type_id)->load($entity_id);
// Changes: wrapped the original code in a translation check, changed the $entity variable name, then repeated for the second language.
if ($entity->hasTranslation('en')) {
$entity_en = $entity->getTranslation('en');
$images = $entity_en->get($image_field_name)->getValue();
$entity_en->set($media_field_name, NULL);
foreach ($images as $image) {
$media = image_field_to_media_get_media_entity($image, 'en');
$entity_en->get($media_field_name)->appendItem($media);
}
$entity_en->save();
}
if ($entity->hasTranslation('fr')) {
$entity_fr = $entity->getTranslation('fr');
$images = $entity_fr->get($image_field_name)->getValue();
$entity_fr->set($media_field_name, NULL);
foreach ($images as $image) {
$media = image_field_to_media_get_media_entity($image, 'fr');
$entity_fr->get($media_field_name)->appendItem($media);
}
$entity_fr->save();
}
// End of main changes. Two more small ones below.
$context['results']['updated_entities']++;
...
...
// Added $langcode parameter.
function image_field_to_media_get_media_entity(array $image, $langcode) {
...
$media = \Drupal::entityTypeManager()
->getStorage('media')
->create([
'bundle' => 'image',
'langcode' => $langcode, // Added this line.
'uid' => 1,
]);
...