FieldConfig.php 11.3 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\Component\Utility\SafeMarkup;
11
use Drupal\Core\Entity\EntityStorageInterface;
12
use Drupal\Core\Field\FieldConfigBase;
13
use Drupal\Core\Field\FieldException;
14
use Drupal\field\FieldStorageConfigInterface;
15
use Drupal\field\FieldConfigInterface;
16
17

/**
18
 * Defines the Field entity.
19
 *
20
 * @ConfigEntityType(
21
22
 *   id = "field_config",
 *   label = @Translation("Field"),
23
 *   handlers = {
24
25
 *     "access" = "Drupal\field\FieldConfigAccessControlHandler",
 *     "storage" = "Drupal\field\FieldConfigStorage"
26
 *   },
27
 *   config_prefix = "field",
28
29
 *   entity_keys = {
 *     "id" = "id",
30
 *     "label" = "label"
31
32
33
 *   }
 * )
 */
34
class FieldConfig extends FieldConfigBase implements FieldConfigInterface {
35
36

  /**
37
   * Flag indicating whether the field is deleted.
38
   *
39
   * The delete() method marks the field as "deleted" and removes the
40
41
42
43
   * 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.
   *
44
   * Deleted fields stay out of the regular entity lifecycle (notably, their
45
46
47
48
   * values are not populated in loaded entities, and are not saved back).
   *
   * @var bool
   */
49
  public $deleted = FALSE;
50

51
  /**
52
   * The associated FieldStorageConfig entity.
53
   *
54
   * @var \Drupal\field\Entity\FieldStorageConfig
55
   */
56
  protected $fieldStorage;
57

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

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

110
111
112
113
  /**
   * {@inheritdoc}
   */
  public function postCreate(EntityStorageInterface $storage) {
114
115
    parent::postCreate($storage);

116
    // Validate that we have a valid storage for this field. This throws an
117
    // exception if the storage is invalid.
118
    $this->getFieldStorageDefinition();
119

120
121
    // 'Label' defaults to the field name (mostly useful for fields created in
    // tests).
122
    if (empty($this->label)) {
123
      $this->label = $this->getName();
124
125
126
    }
  }

127
  /**
128
   * Overrides \Drupal\Core\Entity\Entity::preSave().
129
   *
130
   * @throws \Drupal\Core\Field\FieldException
131
   *   If the field definition is invalid.
132
133
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
134
   */
135
  public function preSave(EntityStorageInterface $storage) {
136
137
138
    $entity_manager = \Drupal::entityManager();
    $field_type_manager = \Drupal::service('plugin.manager.field.field_type');

139
    $storage_definition = $this->getFieldStorageDefinition();
140

141
142
143
    // 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.
144
    $default_settings = $field_type_manager->getDefaultFieldSettings($storage_definition->getType());
145
146
    $this->settings = array_intersect_key($this->settings, $default_settings) + $default_settings;

147
    if ($this->isNew()) {
148
      // Notify the entity storage.
149
      $entity_manager->getStorage($this->entity_type)->onFieldDefinitionCreate($this);
150
151
    }
    else {
152
153
      // Some updates are always disallowed.
      if ($this->entity_type != $this->original->entity_type) {
154
        throw new FieldException("Cannot change an existing field's entity_type.");
155
      }
156
      if ($this->bundle != $this->original->bundle && empty($this->bundleRenameAllowed)) {
157
        throw new FieldException("Cannot change an existing field's bundle.");
158
      }
159
      if ($storage_definition->uuid() != $this->original->getFieldStorageDefinition()->uuid()) {
160
        throw new FieldException("Cannot change an existing field's storage.");
161
      }
162
      // Notify the entity storage.
163
      $entity_manager->getStorage($this->entity_type)->onFieldDefinitionUpdate($this, $this->original);
164
    }
165
166

    parent::preSave($storage);
167
168
169
170
171
172
173
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
174
    // Mark the field_storage_config as a a dependency.
175
    $this->addDependency('config', $this->getFieldStorageDefinition()->getConfigDependencyName());
176
    return $this->dependencies;
177
  }
178

179
  /**
180
   * {@inheritdoc}
181
   */
182
  public static function preDelete(EntityStorageInterface $storage, array $fields) {
183
184
    $state = \Drupal::state();

185
    parent::preDelete($storage, $fields);
186
    // Keep the field definitions in the state storage so we can use them
187
    // later during field_purge_batch().
188
189
190
191
    $deleted_fields = $state->get('field.field.deleted') ?: array();
    foreach ($fields as $field) {
      if (!$field->deleted) {
        $config = $field->toArray();
192
        $config['deleted'] = TRUE;
193
194
        $config['field_storage_uuid'] = $field->getFieldStorageDefinition()->uuid();
        $deleted_fields[$field->uuid()] = $config;
195
      }
196
    }
197
    $state->set('field.field.deleted', $deleted_fields);
198
199
  }

200
  /**
201
   * {@inheritdoc}
202
   */
203
  public static function postDelete(EntityStorageInterface $storage, array $fields) {
204
    // Clear the cache upfront, to refresh the results of getBundles().
205
    \Drupal::entityManager()->clearCachedFieldDefinitions();
206

207
    // Notify the entity storage.
208
209
210
    foreach ($fields as $field) {
      if (!$field->deleted) {
        \Drupal::entityManager()->getStorage($field->entity_type)->onFieldDefinitionDelete($field);
211
      }
212
    }
213

214
215
    // If this is part of a configuration synchronization then the following
    // configuration updates are not necessary.
216
    $entity = reset($fields);
217
218
219
220
    if ($entity->isSyncing()) {
      return;
    }

221
222
    // Delete the associated field storages if they are not used anymore and are
    // not persistent.
223
    $storages_to_delete = array();
224
225
    foreach ($fields as $field) {
      $storage_definition = $field->getFieldStorageDefinition();
226
      if (!$field->deleted && !$field->isUninstalling() && $storage_definition->isDeletable()) {
227
228
        // Key by field UUID to avoid deleting the same storage twice.
        $storages_to_delete[$storage_definition->uuid()] = $storage_definition;
229
      }
230
    }
231
232
    if ($storages_to_delete) {
      \Drupal::entityManager()->getStorage('field_storage_config')->delete($storages_to_delete);
233
    }
234
235
  }

236
237
238
  /**
   * {@inheritdoc}
   */
239
240
241
  protected function linkTemplates() {
    $link_templates = parent::linkTemplates();
    if (\Drupal::moduleHandler()->moduleExists('field_ui')) {
242
243
244
      $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';
245

246
247
      if (isset($link_templates['config-translation-overview'])) {
        $link_templates["config-translation-overview.{$this->entity_type}"] = "entity.field_config.config_translation_overview.{$this->entity_type}";
248
      }
249
    }
250
251
    return $link_templates;
  }
252

253
254
255
  /**
   * {@inheritdoc}
   */
256
257
  protected function urlRouteParameters($rel) {
    $parameters = parent::urlRouteParameters($rel);
258
259
    $entity_type = \Drupal::entityManager()->getDefinition($this->entity_type);
    $parameters[$entity_type->getBundleEntityType()] = $this->bundle;
260
    return $parameters;
261
262
  }

263
264
265
  /**
   * {@inheritdoc}
   */
266
267
  public function isDeleted() {
    return $this->deleted;
268
269
  }

270
271
272
  /**
   * {@inheritdoc}
   */
273
274
275
276
  public function getFieldStorageDefinition() {
    if (!$this->fieldStorage) {
      $fields = $this->entityManager()->getFieldStorageDefinitions($this->entity_type);
      if (!isset($fields[$this->field_name])) {
277
        throw new FieldException(SafeMarkup::format('Attempt to create a field @field_name that does not exist on entity type @entity_type.', array('@field_name' => $this->field_name, '@entity_type' => $this->entity_type)));      }
278
      if (!$fields[$this->field_name] instanceof FieldStorageConfigInterface) {
279
        throw new FieldException(SafeMarkup::format('Attempt to create a configurable field of non-configurable field storage @field_name.', array('@field_name' => $this->field_name, '@entity_type' => $this->entity_type)));
280
281
      }
      $this->fieldStorage = $fields[$this->field_name];
282
    }
283
284

    return $this->fieldStorage;
285
286
  }

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
  /**
   * {@inheritdoc}
   */
  public function isDisplayConfigurable($context) {
    return TRUE;
  }

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

302
303
304
305
306
307
308
309
310
311
312
313
314
315
  /**
   * {@inheritdoc}
   */
  public function isReadOnly() {
    return FALSE;
  }

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

316
317
318
319
320
321
322
323
324
325
326
  /**
   * 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
327
   *   The field config entity if one exists for the provided field
328
329
330
   *   name, otherwise NULL.
   */
  public static function loadByName($entity_type_id, $bundle, $field_name) {
331
    return \Drupal::entityManager()->getStorage('field_config')->load($entity_type_id . '.' . $bundle . '.' . $field_name);
332
333
  }

334
}