Drupal 9 image field migration

Faced up with migration form Drupal 7 to 8(9). Migration process was processed with standart module "upgrade" from UI. The task was to migrate an old image field to media.

Solution was found with hook_update.

First of all check if the image is already present in DB. It could be by the previous runs etc

$medias_thumb = \Drupal::entityTypeManager()

->getStorage('media')

->loadByProperties([

'bundle' => [$convert['media_bundle']],

'name' => $node->{$old_field}->entity->label()]

);


if (!empty($medias_thumb)) {

$new_field = $convert['new_node_image_field'];

$node->{$new_field}->entity = reset($medias_thumb);

$node->save();


\Drupal::logger('image_to_media')->notice(

sprintf('Reuse IMAGE_THUMB for node "%s".', $node->getTitle())

);

}

 

If there is no image in the DB load it and create a copy in new field.

if (!empty($medias)) {

$media = reset($medias);

$file_id = $media->field_media_image->target_id;

$file = File::load($file_id);

$new_field = $convert['new_node_image_field'];

$node->{$new_field}->entity = _mymodule_create_media_image_entity(

$convert['media_bundle'],

$file,

$node->{$old_field}->alt

);

$node->save();


$media_ids_remove[] = $media->id();

\Drupal::logger('image_to_media')->notice(

sprintf('Reuse media for node "%s".', $node->getTitle())

);

}

 

Full version of script located here https://gist.github.com/onesixromcom/d8be7e86c25821aea30a6fb5f380ddf2

To run this hook use drush command:

drush php-eval "module_load_install('mymodule_custom'); mymodule_custom_update_8801();"

Add new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed.
 ooooooo  ooooo  oooo   oooooo   oooo                          oooooooooooo 
`8888 d8' `888 `888. .8' `888' `8
Y888..8P 888 `888. .8' oo.ooooo. oooooooo 888
`8888' 888 `888.8' 888' `88b d'""7d8P 888oooo8
.8PY888. 888 `888' 888 888 .d8P' 888 "
d8' `888b 888 888 888 888 .d8P' .P 888
o888o o88888o o888o o888o 888bod8P' d8888888P o888o
888
o888o
Enter the code depicted in ASCII art style.