You are here

public function FieldManager::createNewReferenceField in Scheduled Updates 8

Creates a new Entity Reference field that will reference the updates of this type.

Parameters

array $new_field_settings:

\Drupal\scheduled_updates\ScheduledUpdateTypeInterface $update_type:

Return value

mixed

Overrides FieldManagerInterface::createNewReferenceField

File

src/FieldManager.php, line 155
Contains \Drupal\scheduled_updates\FieldManager.

Class

FieldManager
Field Manager for handling fields for Scheduled Updates.

Namespace

Drupal\scheduled_updates

Code

public function createNewReferenceField(array $new_field_settings, ScheduledUpdateTypeInterface $scheduled_update_type) {
  $entity_type = $scheduled_update_type
    ->getUpdateEntityType();
  $field_name = $this
    ->createNonExistingFieldName($new_field_settings['field_name'], $entity_type);
  $label = $new_field_settings['label'];
  if ($new_field_settings['cardinality'] == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
    $new_field_settings['cardinality_number'] = FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED;
  }
  $field_storage_values = [
    'field_name' => $field_name,
    'entity_type' => $entity_type,
    'type' => 'entity_reference',
    'translatable' => FALSE,
    'settings' => [
      'target_type' => 'scheduled_update',
    ],
    'cardinality' => $new_field_settings['cardinality_number'],
  ];
  FieldStorageConfig::create($field_storage_values)
    ->save();
  $bundles = array_filter($new_field_settings['bundles']);
  foreach ($bundles as $bundle) {
    $field_values = [
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'label' => $label,
      // Field translatability should be explicitly enabled by the users.
      'translatable' => FALSE,
      'settings' => [
        'handler_settings' => [
          'target_bundles' => [
            $scheduled_update_type
              ->id(),
          ],
        ],
      ],
    ];
    $field = FieldConfig::create($field_values);
    $field
      ->save();
    $this
      ->addToDefaultFormDisplay($entity_type, $bundle, $label, $field_name);
  }
}