function AddToAllBundles::apply

Same name in other branches
  1. 10 core/modules/field/src/Plugin/ConfigAction/AddToAllBundles.php \Drupal\field\Plugin\ConfigAction\AddToAllBundles::apply()

Overrides ConfigActionPluginInterface::apply

File

core/modules/field/src/Plugin/ConfigAction/AddToAllBundles.php, line 52

Class

AddToAllBundles
Adds a field to all bundles of its target entity type.

Namespace

Drupal\field\Plugin\ConfigAction

Code

public function apply(string $configName, mixed $value) : void {
    assert(is_array($value));
    $field_storage = $this->configManager
        ->loadConfigEntityByName($configName);
    assert($field_storage instanceof FieldStorageConfigInterface);
    $storage = $this->entityTypeManager
        ->getStorage('field_config');
    $entity_type_id = $field_storage->getTargetEntityTypeId();
    $field_name = $field_storage->getName();
    $existing_fields = $storage->getQuery()
        ->condition('entity_type', $entity_type_id)
        ->condition('field_name', $field_name)
        ->execute();
    // Get all bundles of the target entity type.
    $bundles = array_keys($this->entityTypeBundleInfo
        ->getBundleInfo($entity_type_id));
    foreach ($bundles as $bundle) {
        $id = "{$entity_type_id}.{$bundle}.{$field_name}";
        if (in_array($id, $existing_fields, TRUE)) {
            if (empty($value['fail_if_exists'])) {
                continue;
            }
            throw new ConfigActionException(sprintf('Field %s already exists.', $id));
        }
        $storage->create([
            'label' => $value['label'],
            'bundle' => $bundle,
            'description' => $value['description'],
            'field_storage' => $field_storage,
        ])
            ->save();
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.