FieldConfig.php 12.8 KB
Newer Older
1
2
<?php

3
namespace Drupal\field\Entity;
4

5
use Drupal\Core\Entity\EntityStorageInterface;
6
use Drupal\Core\Entity\FieldableEntityStorageInterface;
7
use Drupal\Core\Field\FieldConfigBase;
8
use Drupal\Core\Field\FieldException;
9
use Drupal\field\FieldStorageConfigInterface;
10
use Drupal\field\FieldConfigInterface;
11
12

/**
13
 * Defines the Field entity.
14
 *
15
 * @ConfigEntityType(
16
17
 *   id = "field_config",
 *   label = @Translation("Field"),
18
19
20
21
22
23
24
 *   label_collection = @Translation("Fields"),
 *   label_singular = @Translation("field"),
 *   label_plural = @Translation("fields"),
 *   label_count = @PluralTranslation(
 *     singular = "@count field",
 *     plural = "@count fields",
 *   ),
25
 *   handlers = {
26
27
 *     "access" = "Drupal\field\FieldConfigAccessControlHandler",
 *     "storage" = "Drupal\field\FieldConfigStorage"
28
 *   },
29
 *   config_prefix = "field",
30
31
 *   entity_keys = {
 *     "id" = "id",
32
 *     "label" = "label"
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 *   },
 *   config_export = {
 *     "id",
 *     "field_name",
 *     "entity_type",
 *     "bundle",
 *     "label",
 *     "description",
 *     "required",
 *     "translatable",
 *     "default_value",
 *     "default_value_callback",
 *     "settings",
 *     "field_type",
47
48
49
 *   }
 * )
 */
50
class FieldConfig extends FieldConfigBase implements FieldConfigInterface {
51
52

  /**
53
   * Flag indicating whether the field is deleted.
54
   *
55
   * The delete() method marks the field as "deleted" and removes the
56
57
58
59
   * corresponding entry from the config storage, but keeps its definition in
   * the state storage while field data is purged by a separate
   * garbage-collection process.
   *
60
   * Deleted fields stay out of the regular entity lifecycle (notably, their
61
62
63
64
   * values are not populated in loaded entities, and are not saved back).
   *
   * @var bool
   */
65
  protected $deleted = FALSE;
66

67
  /**
68
   * The associated FieldStorageConfig entity.
69
   *
70
   * @var \Drupal\field\Entity\FieldStorageConfig
71
   */
72
  protected $fieldStorage;
73

74
  /**
75
   * Constructs a FieldConfig object.
76
   *
77
   * In most cases, Field entities are created via
78
   * FieldConfig::create($values), where $values is the same
79
80
   * parameter as in this constructor.
   *
81
   * @param array $values
82
   *   An array of field properties, keyed by property name. The
83
   *   storage associated with the field can be specified either with:
84
85
86
   *   - field_storage: the FieldStorageConfigInterface object,
   *   or by referring to an existing field storage in the current configuration
   *   with:
87
88
89
   *   - field_name: The field name.
   *   - entity_type: The entity type.
   *   Additionally, a 'bundle' property is required to indicate the entity
90
   *   bundle to which the field is attached to. Other array elements will be
91
92
   *   used to set the corresponding properties on the class; see the class
   *   property documentation for details.
93
   */
94
  public function __construct(array $values, $entity_type = 'field_config') {
95
    // Allow either an injected FieldStorageConfig object, or a field_name and
96
    // entity_type.
97
98
    if (isset($values['field_storage'])) {
      if (!$values['field_storage'] instanceof FieldStorageConfigInterface) {
99
        throw new FieldException('Attempt to create a configurable field for a non-configurable field storage.');
100
      }
101
102
103
      $field_storage = $values['field_storage'];
      $values['field_name'] = $field_storage->getName();
      $values['entity_type'] = $field_storage->getTargetEntityTypeId();
104
105
106
      // The internal property is fieldStorage, not field_storage.
      unset($values['field_storage']);
      $values['fieldStorage'] = $field_storage;
107
    }
108
109
    else {
      if (empty($values['field_name'])) {
110
        throw new FieldException('Attempt to create a field without a field_name.');
111
112
      }
      if (empty($values['entity_type'])) {
113
        throw new FieldException("Attempt to create a field '{$values['field_name']}' without an entity_type.");
114
      }
115
    }
116
    // 'bundle' is required in either case.
117
    if (empty($values['bundle'])) {
118
      throw new FieldException("Attempt to create a field '{$values['field_name']}' without a bundle.");
119
120
121
122
123
    }

    parent::__construct($values, $entity_type);
  }

124
125
126
127
  /**
   * {@inheritdoc}
   */
  public function postCreate(EntityStorageInterface $storage) {
128
129
    parent::postCreate($storage);

130
    // Validate that we have a valid storage for this field. This throws an
131
    // exception if the storage is invalid.
132
    $this->getFieldStorageDefinition();
133

134
135
    // 'Label' defaults to the field name (mostly useful for fields created in
    // tests).
136
    if (empty($this->label)) {
137
      $this->label = $this->getName();
138
139
140
    }
  }

141
  /**
142
   * Overrides \Drupal\Core\Entity\Entity::preSave().
143
   *
144
   * @throws \Drupal\Core\Field\FieldException
145
   *   If the field definition is invalid.
146
147
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
148
   */
149
  public function preSave(EntityStorageInterface $storage) {
150
151
152
    $entity_manager = \Drupal::entityManager();
    $field_type_manager = \Drupal::service('plugin.manager.field.field_type');

153
    $storage_definition = $this->getFieldStorageDefinition();
154

155
156
157
    // Filter out unknown settings and make sure all settings are present, so
    // that a complete field definition is passed to the various hooks and
    // written to config.
158
    $default_settings = $field_type_manager->getDefaultFieldSettings($storage_definition->getType());
159
160
    $this->settings = array_intersect_key($this->settings, $default_settings) + $default_settings;

161
    if ($this->isNew()) {
162
      // Notify the entity storage.
163
      \Drupal::service('field_definition.listener')->onFieldDefinitionCreate($this);
164
165
    }
    else {
166
167
      // Some updates are always disallowed.
      if ($this->entity_type != $this->original->entity_type) {
168
        throw new FieldException("Cannot change an existing field's entity_type.");
169
      }
170
      if ($this->bundle != $this->original->bundle) {
171
        throw new FieldException("Cannot change an existing field's bundle.");
172
      }
173
      if ($storage_definition->uuid() != $this->original->getFieldStorageDefinition()->uuid()) {
174
        throw new FieldException("Cannot change an existing field's storage.");
175
      }
176
      // Notify the entity storage.
177
      \Drupal::service('field_definition.listener')->onFieldDefinitionUpdate($this, $this->original);
178
    }
179
180

    parent::preSave($storage);
181
182
183
184
185
186
187
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
188
    // Mark the field_storage_config as a dependency.
189
    $this->addDependency('config', $this->getFieldStorageDefinition()->getConfigDependencyName());
190
    return $this;
191
  }
192

193
  /**
194
   * {@inheritdoc}
195
   */
196
  public static function preDelete(EntityStorageInterface $storage, array $fields) {
197
198
    /** @var \Drupal\Core\Field\DeletedFieldsRepositoryInterface $deleted_fields_repository */
    $deleted_fields_repository = \Drupal::service('entity_field.deleted_fields_repository');
199
    $entity_type_manager = \Drupal::entityTypeManager();
200

201
    parent::preDelete($storage, $fields);
202

203
204
    // Keep the field definitions in the deleted fields repository so we can use
    // them later during field_purge_batch().
205
    /** @var \Drupal\field\FieldConfigInterface $field */
206
    foreach ($fields as $field) {
207
208
209
210
      // Only mark a field for purging if there is data. Otherwise, just remove
      // it.
      $target_entity_storage = $entity_type_manager->getStorage($field->getTargetEntityTypeId());
      if (!$field->deleted && $target_entity_storage instanceof FieldableEntityStorageInterface && $target_entity_storage->countFieldData($field->getFieldStorageDefinition(), TRUE)) {
211
212
213
214
        $field = clone $field;
        $field->deleted = TRUE;
        $field->fieldStorage = NULL;
        $deleted_fields_repository->addFieldDefinition($field);
215
      }
216
217
218
    }
  }

219
  /**
220
   * {@inheritdoc}
221
   */
222
  public static function postDelete(EntityStorageInterface $storage, array $fields) {
223
    // Clear the cache upfront, to refresh the results of getBundles().
224
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
225

226
    // Notify the entity storage.
227
228
    foreach ($fields as $field) {
      if (!$field->deleted) {
229
        \Drupal::service('field_definition.listener')->onFieldDefinitionDelete($field);
230
      }
231
    }
232

233
234
    // If this is part of a configuration synchronization then the following
    // configuration updates are not necessary.
235
    $entity = reset($fields);
236
237
238
239
    if ($entity->isSyncing()) {
      return;
    }

240
241
    // Delete the associated field storages if they are not used anymore and are
    // not persistent.
242
    $storages_to_delete = [];
243
244
    foreach ($fields as $field) {
      $storage_definition = $field->getFieldStorageDefinition();
245
      if (!$field->deleted && !$field->isUninstalling() && $storage_definition->isDeletable()) {
246
247
        // Key by field UUID to avoid deleting the same storage twice.
        $storages_to_delete[$storage_definition->uuid()] = $storage_definition;
248
      }
249
    }
250
251
    if ($storages_to_delete) {
      \Drupal::entityManager()->getStorage('field_storage_config')->delete($storages_to_delete);
252
    }
253
254
  }

255
256
257
  /**
   * {@inheritdoc}
   */
258
259
260
  protected function linkTemplates() {
    $link_templates = parent::linkTemplates();
    if (\Drupal::moduleHandler()->moduleExists('field_ui')) {
261
262
263
      $link_templates["{$this->entity_type}-field-edit-form"] = 'entity.field_config.' . $this->entity_type . '_field_edit_form';
      $link_templates["{$this->entity_type}-storage-edit-form"] = 'entity.field_config.' . $this->entity_type . '_storage_edit_form';
      $link_templates["{$this->entity_type}-field-delete-form"] = 'entity.field_config.' . $this->entity_type . '_field_delete_form';
264

265
266
      if (isset($link_templates['config-translation-overview'])) {
        $link_templates["config-translation-overview.{$this->entity_type}"] = "entity.field_config.config_translation_overview.{$this->entity_type}";
267
      }
268
    }
269
270
    return $link_templates;
  }
271

272
273
274
  /**
   * {@inheritdoc}
   */
275
276
  protected function urlRouteParameters($rel) {
    $parameters = parent::urlRouteParameters($rel);
277
    $entity_type = \Drupal::entityManager()->getDefinition($this->entity_type);
278
279
    $bundle_parameter_key = $entity_type->getBundleEntityType() ?: 'bundle';
    $parameters[$bundle_parameter_key] = $this->bundle;
280
    return $parameters;
281
282
  }

283
284
285
  /**
   * {@inheritdoc}
   */
286
287
  public function isDeleted() {
    return $this->deleted;
288
289
  }

290
291
292
  /**
   * {@inheritdoc}
   */
293
294
  public function getFieldStorageDefinition() {
    if (!$this->fieldStorage) {
295
296
      $field_storage_definition = NULL;

297
      $field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($this->entity_type);
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
      if (isset($field_storage_definitions[$this->field_name])) {
        $field_storage_definition = $field_storage_definitions[$this->field_name];
      }
      // If this field has been deleted, try to find its field storage
      // definition in the deleted fields repository.
      elseif ($this->deleted) {
        $deleted_storage_definitions = \Drupal::service('entity_field.deleted_fields_repository')->getFieldStorageDefinitions();
        foreach ($deleted_storage_definitions as $deleted_storage_definition) {
          if ($deleted_storage_definition->getName() === $this->field_name) {
            $field_storage_definition = $deleted_storage_definition;
          }
        }
      }

      if (!$field_storage_definition) {
313
        throw new FieldException("Attempt to create a field {$this->field_name} that does not exist on entity type {$this->entity_type}.");
314
      }
315
      if (!$field_storage_definition instanceof FieldStorageConfigInterface) {
316
        throw new FieldException("Attempt to create a configurable field of non-configurable field storage {$this->field_name}.");
317
      }
318
      $this->fieldStorage = $field_storage_definition;
319
    }
320
321

    return $this->fieldStorage;
322
323
  }

324
325
326
327
328
329
330
331
332
333
334
335
  /**
   * {@inheritdoc}
   */
  public function isDisplayConfigurable($context) {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getDisplayOptions($display_context) {
    // Hide configurable fields by default.
336
    return ['region' => 'hidden'];
337
338
  }

339
340
341
342
343
344
345
346
347
348
349
350
351
352
  /**
   * {@inheritdoc}
   */
  public function isReadOnly() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function isComputed() {
    return FALSE;
  }

353
354
355
356
357
358
359
  /**
   * {@inheritdoc}
   */
  public function getUniqueIdentifier() {
    return $this->uuid();
  }

360
361
362
363
364
365
366
367
368
369
370
  /**
   * Loads a field config entity based on the entity type and field name.
   *
   * @param string $entity_type_id
   *   ID of the entity type.
   * @param string $bundle
   *   Bundle name.
   * @param string $field_name
   *   Name of the field.
   *
   * @return static
371
   *   The field config entity if one exists for the provided field
372
373
374
   *   name, otherwise NULL.
   */
  public static function loadByName($entity_type_id, $bundle, $field_name) {
375
    return \Drupal::entityManager()->getStorage('field_config')->load($entity_type_id . '.' . $bundle . '.' . $field_name);
376
377
  }

378
}