You are here

private function MediaMigrateCommands::createMediaField in Migrate File Entities to Media Entities 8

Create a new entity media reference field.

Parameters

$entity_type:

$bundle:

\Drupal\field\Entity\FieldConfig $existing_field:

$new_field_name:

$target_media_bundle:

Return value

\Drupal\Core\Field\FieldDefinitionInterface

1 call to MediaMigrateCommands::createMediaField()
MediaMigrateCommands::migrateFileFields in src/Commands/MediaMigrateCommands.php
Create media destination fields.

File

src/Commands/MediaMigrateCommands.php, line 171

Class

MediaMigrateCommands
Drush 9 commands for migrate_file_to_media.

Namespace

Drupal\migrate_file_to_media\Commands

Code

private function createMediaField($entity_type, $bundle, FieldConfig $existing_field, $new_field_name, $target_media_bundle) {
  $field = FieldConfig::loadByName($entity_type, $bundle, $new_field_name);
  if (empty($field)) {

    // Load existing field storage.
    $field_storage = FieldStorageConfig::loadByName($entity_type, $new_field_name);

    // Create a field storage if none found.
    if (empty($field_storage)) {
      $field_storage = FieldStorageConfig::create([
        'field_name' => $new_field_name,
        'entity_type' => $entity_type,
        'cardinality' => $existing_field
          ->getFieldStorageDefinition()
          ->getCardinality(),
        'type' => 'entity_reference',
        'settings' => [
          'target_type' => 'media',
        ],
      ]);
      $field_storage
        ->save();
    }
    $field = \Drupal::service('entity_type.manager')
      ->getStorage('field_config')
      ->create([
      'field_storage' => $field_storage,
      'bundle' => $bundle,
      'label' => $existing_field
        ->getLabel() . ' Media',
      'settings' => [
        'handler' => 'default:media',
        'handler_settings' => [
          'target_bundles' => [
            $target_media_bundle => $target_media_bundle,
          ],
        ],
      ],
    ]);
    $field
      ->save();

    // Update Form Widget.
    $type = $entity_type . '.' . $bundle . '.default';

    /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $definition */
    $definition = $this->entityTypeManager
      ->getStorage('entity_form_display')
      ->load($type);
    $definition
      ->setComponent($new_field_name, [
      'type' => 'entity_reference_autocomplete',
    ])
      ->save();
  }
  return $field;
}