FieldConfig.php 11.2 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\field\Entity\FieldConfig.
6
7
 */

8
namespace Drupal\field\Entity;
9

10
use Drupal\Core\Entity\EntityStorageInterface;
11
use Drupal\Core\Field\FieldConfigBase;
12
use Drupal\Core\Field\FieldException;
13
use Drupal\field\FieldStorageConfigInterface;
14
use Drupal\field\FieldConfigInterface;
15
16

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

  /**
50
   * Flag indicating whether the field is deleted.
51
   *
52
   * The delete() method marks the field as "deleted" and removes the
53
54
55
56
   * 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.
   *
57
   * Deleted fields stay out of the regular entity lifecycle (notably, their
58
59
60
61
   * values are not populated in loaded entities, and are not saved back).
   *
   * @var bool
   */
62
  protected $deleted = FALSE;
63

64
  /**
65
   * The associated FieldStorageConfig entity.
66
   *
67
   * @var \Drupal\field\Entity\FieldStorageConfig
68
   */
69
  protected $fieldStorage;
70

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

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

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

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

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

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

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

154
155
156
    // 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.
157
    $default_settings = $field_type_manager->getDefaultFieldSettings($storage_definition->getType());
158
159
    $this->settings = array_intersect_key($this->settings, $default_settings) + $default_settings;

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

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

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

192
  /**
193
   * {@inheritdoc}
194
   */
195
  public static function preDelete(EntityStorageInterface $storage, array $fields) {
196
197
    $state = \Drupal::state();

198
    parent::preDelete($storage, $fields);
199
    // Keep the field definitions in the state storage so we can use them
200
    // later during field_purge_batch().
201
202
203
204
    $deleted_fields = $state->get('field.field.deleted') ?: array();
    foreach ($fields as $field) {
      if (!$field->deleted) {
        $config = $field->toArray();
205
        $config['deleted'] = TRUE;
206
207
        $config['field_storage_uuid'] = $field->getFieldStorageDefinition()->uuid();
        $deleted_fields[$field->uuid()] = $config;
208
      }
209
    }
210
    $state->set('field.field.deleted', $deleted_fields);
211
212
  }

213
  /**
214
   * {@inheritdoc}
215
   */
216
  public static function postDelete(EntityStorageInterface $storage, array $fields) {
217
    // Clear the cache upfront, to refresh the results of getBundles().
218
    \Drupal::entityManager()->clearCachedFieldDefinitions();
219

220
    // Notify the entity storage.
221
222
    foreach ($fields as $field) {
      if (!$field->deleted) {
223
        \Drupal::entityManager()->onFieldDefinitionDelete($field);
224
      }
225
    }
226

227
228
    // If this is part of a configuration synchronization then the following
    // configuration updates are not necessary.
229
    $entity = reset($fields);
230
231
232
233
    if ($entity->isSyncing()) {
      return;
    }

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

249
250
251
  /**
   * {@inheritdoc}
   */
252
253
254
  protected function linkTemplates() {
    $link_templates = parent::linkTemplates();
    if (\Drupal::moduleHandler()->moduleExists('field_ui')) {
255
256
257
      $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';
258

259
260
      if (isset($link_templates['config-translation-overview'])) {
        $link_templates["config-translation-overview.{$this->entity_type}"] = "entity.field_config.config_translation_overview.{$this->entity_type}";
261
      }
262
    }
263
264
    return $link_templates;
  }
265

266
267
268
  /**
   * {@inheritdoc}
   */
269
270
  protected function urlRouteParameters($rel) {
    $parameters = parent::urlRouteParameters($rel);
271
    $entity_type = \Drupal::entityManager()->getDefinition($this->entity_type);
272
273
    $bundle_parameter_key = $entity_type->getBundleEntityType() ?: 'bundle';
    $parameters[$bundle_parameter_key] = $this->bundle;
274
    return $parameters;
275
276
  }

277
278
279
  /**
   * {@inheritdoc}
   */
280
281
  public function isDeleted() {
    return $this->deleted;
282
283
  }

284
285
286
  /**
   * {@inheritdoc}
   */
287
288
289
290
  public function getFieldStorageDefinition() {
    if (!$this->fieldStorage) {
      $fields = $this->entityManager()->getFieldStorageDefinitions($this->entity_type);
      if (!isset($fields[$this->field_name])) {
291
        throw new FieldException("Attempt to create a field {$this->field_name} that does not exist on entity type {$this->entity_type}.");
292
      }
293
      if (!$fields[$this->field_name] instanceof FieldStorageConfigInterface) {
294
        throw new FieldException("Attempt to create a configurable field of non-configurable field storage {$this->field_name}.");
295
296
      }
      $this->fieldStorage = $fields[$this->field_name];
297
    }
298
299

    return $this->fieldStorage;
300
301
  }

302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  /**
   * {@inheritdoc}
   */
  public function isDisplayConfigurable($context) {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getDisplayOptions($display_context) {
    // Hide configurable fields by default.
    return array('type' => 'hidden');
  }

317
318
319
320
321
322
323
324
325
326
327
328
329
330
  /**
   * {@inheritdoc}
   */
  public function isReadOnly() {
    return FALSE;
  }

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

331
332
333
334
335
336
337
338
339
340
341
  /**
   * 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
342
   *   The field config entity if one exists for the provided field
343
344
345
   *   name, otherwise NULL.
   */
  public static function loadByName($entity_type_id, $bundle, $field_name) {
346
    return \Drupal::entityManager()->getStorage('field_config')->load($entity_type_id . '.' . $bundle . '.' . $field_name);
347
348
  }

349
}