FieldInstance.php 17.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\field\Plugin\Core\Entity\FieldInstance.
 */

namespace Drupal\field\Plugin\Core\Entity;

10
use Drupal\Core\Entity\Annotation\EntityType;
11 12 13
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\field\FieldException;
14
use Drupal\field\FieldInstanceInterface;
15 16 17 18

/**
 * Defines the Field instance entity.
 *
19
 * @EntityType(
20 21 22
 *   id = "field_instance",
 *   label = @Translation("Field instance"),
 *   module = "field",
23 24 25
 *   controllers = {
 *     "storage" = "Drupal\field\FieldInstanceStorageController"
 *   },
26 27 28 29 30 31 32 33
 *   config_prefix = "field.instance",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   }
 * )
 */
34
class FieldInstance extends ConfigEntityBase implements FieldInstanceInterface {
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

  /**
   * The instance ID (machine name).
   *
   * The ID consists of 3 parts: the entity type, bundle and the field name.
   *
   * Example: node.article.body, user.user.field_main_image.
   *
   * @var string
   */
  public $id;

  /**
   * The instance UUID.
   *
   * This is assigned automatically when the instance is created.
   *
   * @var string
   */
  public $uuid;

  /**
   * The UUID of the field attached to the bundle by this instance.
   *
   * @var string
   */
  public $field_uuid;

  /**
   * The name of the entity type the instance is attached to.
   *
   * @var string
   */
  public $entity_type;

  /**
   * The name of the bundle the instance is attached to.
   *
   * @var string
   */
  public $bundle;

  /**
   * The human-readable label for the instance.
   *
   * This will be used as the title of Form API elements for the field in entity
   * edit forms, or as the label for the field values in displayed entities.
   *
83 84 85
   * If not specified, this defaults to the field_name (mostly useful for field
   * instances created in tests).
   *
86 87 88 89 90 91 92 93 94 95 96 97 98
   * @var string
   */
  public $label;

  /**
   * The instance description.
   *
   * A human-readable description for the field when used with this bundle.
   * For example, the description will be the help text of Form API elements for
   * this instance in entity edit forms.
   *
   * @var string
   */
99
  public $description = '';
100 101 102 103 104

  /**
   * Field-type specific settings.
   *
   * An array of key/value pairs. The keys and default values are defined by the
105
   * field type.
106 107 108
   *
   * @var array
   */
109
  public $settings = array();
110 111 112 113 114 115 116 117 118 119

  /**
   * Flag indicating whether the field is required.
   *
   * TRUE if a value for this field is required when used with this bundle,
   * FALSE otherwise. Currently, required-ness is only enforced at the Form API
   * level in entity edit forms, not during direct API saves.
   *
   * @var bool
   */
120
  public $required = FALSE;
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

  /**
   * Default field value.
   *
   * The default value is used when an entity is created, either:
   * - through an entity creation form; the form elements for the field are
   *   prepopulated with the default value.
   * - through direct API calls (i.e. $entity->save()); the default value is
   *   added if the $entity object provides no explicit entry (actual values or
   *   "the field is empty") for the field.
   *
   * The default value is expressed as a numerically indexed array of items,
   * each item being an array of key/value pairs matching the set of 'columns'
   * defined by the "field schema" for the field type, as exposed in
   * hook_field_schema(). If the number of items exceeds the cardinality of the
   * field, extraneous items will be ignored.
   *
   * This property is overlooked if the $default_value_function is non-empty.
   *
   * Example for a number_integer field:
   * @code
   * array(
   *   array('value' => 1),
   *   array('value' => 2),
   * )
   * @endcode
   *
   * @var array
   */
150
  public $default_value = array();
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

  /**
   * The name of a callback function that returns default values.
   *
   * The function will be called with the following arguments:
   * - \Drupal\Core\Entity\EntityInterface $entity
   *   The entity being created.
   * - \Drupal\field\Plugin\Core\Entity\Field $field
   *   The field object.
   * - \Drupal\field\Plugin\Core\Entity\FieldInstance $instance
   *   The field instance object.
   * - string $langcode
   *   The language of the entity being created.
   * It should return an array of default values, in the same format as the
   * $default_value property.
   *
   * This property takes precedence on the list of fixed values specified in the
   * $default_value property.
   *
   * @var string
   */
172
  public $default_value_function = '';
173 174 175 176 177 178 179 180 181 182 183 184 185 186

  /**
   * Flag indicating whether the instance is deleted.
   *
   * The delete() method marks the instance as "deleted" and removes the
   * 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.
   *
   * Deleted instances stay out of the regular entity lifecycle (notably, their
   * values are not populated in loaded entities, and are not saved back).
   *
   * @var bool
   */
187
  public $deleted = FALSE;
188

189 190 191 192 193 194 195
  /**
   * The field ConfigEntity object corresponding to $field_uuid.
   *
   * @var \Drupal\field\Plugin\Core\Entity\Field
   */
  protected $field;

196 197 198 199 200 201 202
  /**
   * Flag indicating whether the bundle name can be renamed or not.
   *
   * @var bool
   */
  protected $bundle_rename_allowed = FALSE;

203 204 205 206 207 208 209
  /**
   * The original instance.
   *
   * @var \Drupal\field\Plugin\Core\Entity\FieldInstance
   */
  public $original = NULL;

210
  /**
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
   * Constructs a FieldInstance object.
   *
   * @param array $values
   *   An array of field instance properties, keyed by property name. Most
   *   array elements will be used to set the corresponding properties on the
   *   class; see the class property documentation for details. Some array
   *   elements have special meanings and a few are required; these special
   *   elements are:
   *   - field_name: optional. The name of the field this is an instance of.
   *   - field_uuid: optional. Either field_uuid or field_name is required
   *     to build field instance. field_name will gain higher priority.
   *     If field_name is not provided, field_uuid will be checked then.
   *   - entity_type: required.
   *   - bundle: required.
   *
   * In most cases, Field instance entities are created via
   * entity_create('field_instance', $values)), where $values is the same
   * parameter as in this constructor.
   *
   * @see entity_create()
   *
   * @ingroup field_crud
233 234 235 236 237 238
   */
  public function __construct(array $values, $entity_type = 'field_instance') {
    // Accept incoming 'field_name' instead of 'field_uuid', for easier DX on
    // creation of new instances.
    if (isset($values['field_name']) && !isset($values['field_uuid'])) {
      $field = field_info_field($values['field_name']);
239 240
      if (!$field) {
        throw new FieldException(format_string('Attempt to create an instance of unknown, disabled, or deleted field @field_id', array('@field_id' => $values['field_name'])));
241
      }
242
      $values['field_uuid'] = $field->uuid;
243
    }
244 245 246 247 248
    elseif (isset($values['field_uuid'])) {
      $field = field_info_field_by_id($values['field_uuid']);
      // field_info_field_by_id() will not find the field if it is inactive.
      if (!$field) {
        $field = current(field_read_fields(array('uuid' => $values['field_uuid']), array('include_inactive' => TRUE, 'include_deleted' => TRUE)));
249
      }
250
      if (!$field) {
251 252 253
        throw new FieldException(format_string('Attempt to create an instance of unknown field @uuid', array('@uuid' => $values['field_uuid'])));
      }
    }
254
    else {
255 256 257
      throw new FieldException('Attempt to create an instance of an unspecified field.');
    }

258 259 260 261 262
    // At this point, we should have a 'field_uuid' and a Field. Ditch the
    // 'field_name' property if it was provided, and assign the $field property.
    unset($values['field_name']);
    $this->field = $field;

263 264 265 266
    // Discard the 'field_type' entry that is added in config records to ease
    // schema generation. See getExportProperties().
    unset($values['field_type']);

267 268 269 270 271 272 273 274
    // Check required properties.
    if (empty($values['entity_type'])) {
      throw new FieldException(format_string('Attempt to create an instance of field @field_id without an entity type.', array('@field_id' => $this->field->id)));
    }
    if (empty($values['bundle'])) {
      throw new FieldException(format_string('Attempt to create an instance of field @field_id without a bundle.', array('@field_id' => $this->field->id)));
    }

275 276
    // 'Label' defaults to the field ID (mostly useful for field instances
    // created in tests).
277
    $values += array(
278
      'label' => $this->field->id,
279 280 281 282 283 284 285 286
    );
    parent::__construct($values, $entity_type);
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
287
    return $this->entity_type . '.' . $this->bundle . '.' . $this->field->id;
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
  }

  /**
   * {@inheritdoc}
   */
  public function getExportProperties() {
    $names = array(
      'id',
      'uuid',
      'status',
      'langcode',
      'field_uuid',
      'entity_type',
      'bundle',
      'label',
      'description',
      'required',
      'default_value',
      'default_value_function',
      'settings',
    );
    $properties = array();
    foreach ($names as $name) {
      $properties[$name] = $this->get($name);
    }
313 314 315 316 317

    // Additionally, include the field type, that is needed to be able to
    // generate the field-type-dependant parts of the config schema.
    $properties['field_type'] = $this->field->type;

318 319 320 321
    return $properties;
  }

  /**
322 323 324 325 326 327 328 329 330 331
   * Overrides \Drupal\Core\Entity\Entity::save().
   *
   * @return
   *   Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
   *
   * @throws \Drupal\field\FieldException
   *   If the field instance definition is invalid.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
332 333 334
   */
  public function save() {
    if ($this->isNew()) {
335 336 337 338 339 340
      return $this->saveNew();
    }
    else {
      return $this->saveUpdated();
    }
  }
341

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  /**
   * Saves a new field instance definition.
   *
   * @return
   *   SAVED_NEW if the definition was saved.
   *
   * @throws \Drupal\field\FieldException
   *   If the field instance definition is invalid.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
   */
  protected function saveNew() {
    $module_handler = \Drupal::moduleHandler();
    $instance_controller = \Drupal::entityManager()->getStorageController($this->entityType);
357

358 359 360
    // Check that the field can be attached to this entity type.
    if (!empty($this->field->entity_types) && !in_array($this->entity_type, $this->field->entity_types)) {
      throw new FieldException(format_string('Attempt to create an instance of field @field_id on forbidden entity type @entity_type.', array('@field_id' => $this->field->id, '@entity_type' => $this->entity_type)));
361 362
    }

363 364
    // Assign the ID.
    $this->id = $this->id();
365

366
    // Ensure the field instance is unique within the bundle.
367
    if ($prior_instance = $instance_controller->load($this->id)) {
368
      throw new FieldException(format_string('Attempt to create an instance of field @field_id on bundle @bundle that already has an instance of that field.', array('@field_id' => $this->field->id, '@bundle' => $this->bundle)));
369 370
    }

371 372
    // Set the field UUID.
    $this->field_uuid = $this->field->uuid;
373

374 375
    // Ensure default values are present.
    $this->prepareSave();
376 377 378 379 380 381 382 383

    // Save the configuration.
    $result = parent::save();
    field_cache_clear();

    return $result;
  }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
  /**
   * Saves an updated field instance definition.
   *
   * @return
   *   SAVED_UPDATED if the definition was saved.
   *
   * @throws \Drupal\field\FieldException
   *   If the field instance definition is invalid.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   In case of failures at the configuration storage level.
   */
  protected function saveUpdated() {
    $module_handler = \Drupal::moduleHandler();
    $instance_controller = \Drupal::entityManager()->getStorageController($this->entityType);

    $original = $instance_controller->loadUnchanged($this->getOriginalID());
401
    $this->original = $original;
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

    // Some updates are always disallowed.
    if ($this->entity_type != $original->entity_type) {
      throw new FieldException("Cannot change an existing instance's entity_type.");
    }
    if ($this->bundle != $original->bundle && empty($this->bundle_rename_allowed)) {
      throw new FieldException("Cannot change an existing instance's bundle.");
    }
    if ($this->field_uuid != $original->field_uuid) {
      throw new FieldException("Cannot change an existing instance's field.");
    }

    // Ensure default values are present.
    $this->prepareSave();

    // Save the configuration.
    $result = parent::save();
    field_cache_clear();

    return $result;
  }

  /**
   * Prepares the instance definition for saving.
   */
  protected function prepareSave() {
    $field_type_info = field_info_field_types($this->field->type);

    // Set the default instance settings.
    $this->settings += $field_type_info['instance_settings'];
  }

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  /**
   * Overrides \Drupal\Core\Entity\Entity::delete().
   *
   * @param bool $field_cleanup
   *   (optional) If TRUE, the field will be deleted as well if its last
   *   instance is being deleted. If FALSE, it is the caller's responsibility to
   *   handle the case of fields left without instances. Defaults to TRUE.
   */
  public function delete($field_cleanup = TRUE) {
    if (!$this->deleted) {
      $module_handler = \Drupal::moduleHandler();
      $state = \Drupal::state();

      // Delete the configuration of this instance and save the configuration
      // in the key_value table so we can use it later during
      // field_purge_batch().
      $deleted_instances = $state->get('field.instance.deleted') ?: array();
      $config = $this->getExportProperties();
      $config['deleted'] = TRUE;
      $deleted_instances[$this->uuid] = $config;
      $state->set('field.instance.deleted', $deleted_instances);

      parent::delete();

      // Clear the cache.
      field_cache_clear();

      // Mark instance data for deletion by invoking
      // hook_field_storage_delete_instance().
463
      $module_handler->invoke($this->field->storage['module'], 'field_storage_delete_instance', array($this));
464

465 466 467 468 469
      // Remove the instance from the entity form displays.
      if ($form_display = entity_load('entity_form_display', $this->entity_type . '.' . $this->bundle . '.default')) {
        $form_display->removeComponent($this->field->id())->save();
      }

470 471 472 473 474 475 476 477 478 479
      // Remove the instance from the entity displays.
      $ids = array();
      $view_modes = array('default' => array()) + entity_get_view_modes($this->entity_type);
      foreach (array_keys($view_modes) as $view_mode) {
        $ids[] = $this->entity_type . '.' . $this->bundle . '.' . $view_mode;
      }
      foreach (entity_load_multiple('entity_display', $ids) as $display) {
        $display->removeComponent($this->field->id())->save();
      }

480
      // Delete the field itself if we just deleted its last instance.
481 482
      if ($field_cleanup && count($this->field->getBundles()) == 0) {
        $this->field->delete();
483 484 485 486
      }
    }
  }

487 488 489
  /**
   * {@inheritdoc}
   */
490 491 492 493
  public function getField() {
    return $this->field;
  }

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
  /**
   * {@inheritdoc}
   */
  public function getFieldName() {
    return $this->field->id;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldType() {
    return $this->field->type;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldSettings() {
    return $this->settings + $this->field->getFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldSetting($setting_name) {
    if (array_key_exists($setting_name, $this->settings)) {
      return $this->settings[$setting_name];
    }
    else {
      return $this->field->getFieldSetting($setting_name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldPropertyNames() {
    $schema = $this->field->getSchema();
    return array_keys($schema['columns']);
  }

  /**
   * {@inheritdoc}
   */
  public function isFieldTranslatable() {
    return $this->field->translatable;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldLabel() {
    return $this->label();
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldDescription() {
    return $this->description;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldCardinality() {
    return $this->field->cardinality;
  }

  /**
   * {@inheritdoc}
   */
  public function isFieldRequired() {
    return $this->required;
  }

570
  /**
571
   * {@inheritdoc}
572 573 574 575 576 577 578 579 580
   */
  public function allowBundleRename() {
    $this->bundle_rename_allowed = TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function offsetExists($offset) {
581
    return (isset($this->{$offset}) || $offset == 'field_id' || $offset == 'field_name');
582 583 584 585 586 587 588 589 590
  }

  /**
   * {@inheritdoc}
   */
  public function &offsetGet($offset) {
    if ($offset == 'field_id') {
      return $this->field_uuid;
    }
591 592 593
    if ($offset == 'field_name') {
      return $this->field->id;
    }
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    return $this->{$offset};
  }

  /**
   * {@inheritdoc}
   */
  public function offsetSet($offset, $value) {
    if ($offset == 'field_id') {
      $offset = 'field_uuid';
    }
    $this->{$offset} = $value;
  }

  /**
   * {@inheritdoc}
   */
  public function offsetUnset($offset) {
    if ($offset == 'field_id') {
      $offset = 'field_uuid';
    }
    unset($this->{$offset});
  }

617 618 619 620 621 622 623 624 625 626 627 628 629 630
  /**
   * {@inheritdoc}
   */
  public function serialize() {
    // Only store the definition, not external objects or derived data.
    return serialize($this->getExportProperties());
  }

  /**
   * {@inheritdoc}
   */
  public function unserialize($serialized) {
    $this->__construct(unserialize($serialized));
  }
631

632
}