How to convert an existing file/image field to a Media type field

Drupal Version
8

If you have a site that has content populated using a file/image type field and want to convert it to use a Media field type you would need to create a new media type field and re-populate all of the image content. This is not practical for a website with lots of content so we came up with a method to use an update script to automatically populate the new media field from the old file/image field type.

Preparation

If you haven't already, the first step is to create your Media entity. Then create the new media reference field on your existing content type.

Convert

Now place the following code (modified for your field and content type values) in a custom module and run Drupal's update script (/update.php or "drush updb")

<?php
use Drupal\media\Entity\Media;

/**
 * Create media entities from existing file fields.
 */
function MY_MODULE_update_8101() {
 
// Load all of the article and page nodes.
 
$nodes = \Drupal::entityTypeManager()
    ->
getStorage('node')
    ->
loadByProperties(['type' => ['article']]);
  foreach (
$nodes as $node) {
   
// Verify that the file field has a value.
   
if (!empty($node->field_OLD_FIELD_NAME->entity)) { // * use your existing file/image field name here
      // Create the new media entity and assign it to the new field.
      //dpm($node->field_OLD_FIELD_NAME->entity); // * use your existing file/image field name here
     
\Drupal::logger('update_image')->notice(
       
sprintf('preparing image for node "%s".', $node->getTitle())
      );
     
$node->field_NEW_MEDIA_FIELD_NAME->entity = MY_MODULE_create_media_image_entity
       
$node->field_OLD_FIELD_NAME->entity,
       
$node->field_OLD_FIELD_NAME->alt,
      );
     
$node->save();
     
\Drupal::logger('update_image')->notice(
       
sprintf('Updated image for node "%s".', $node->getTitle())
      );
    }
  }
}

/**
 * Creates a media image entity from a file entity.
 *
 * @param $file
 *   The existing file object.
 * @param string $alt
 *   The image alt text.
 *
 * @return \Drupal\media_entity\Entity\Media
 *   The media entity.
 */
function MY_MODULE_create_media_image_entity($file, $alt = NULL) {

 

$media_entity = Media::create([
   
'bundle' => 'teaser_image', // * use your bundle name here
   
'uid' => '1',
   
'name' => $file->alt,
   
'status' => TRUE,
   
'field_media_image_1' => [
     
'target_id' => $file->id(),
     
'alt' => $alt,
    ],
  ]);
 
$media_entity->save();
  return
$media_entity;
}

?>

Author Information

Written by: Shawn Ostermann