Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

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

Parent Feed: 

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.


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.


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")

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()
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
sprintf('preparing image for node "%s".', $node->getTitle())
$node->field_NEW_MEDIA_FIELD_NAME->entity = MY_MODULE_create_media_image_entity
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,
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web