FieldInstance.php 16.5 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 14 15 16 17
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\field\FieldException;

/**
 * Defines the Field instance entity.
 *
18
 * @EntityType(
19 20 21
 *   id = "field_instance",
 *   label = @Translation("Field instance"),
 *   module = "field",
22 23 24
 *   controllers = {
 *     "storage" = "Drupal\field\FieldInstanceStorageController"
 *   },
25 26 27 28 29 30 31 32
 *   config_prefix = "field.instance",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   }
 * )
 */
33
class FieldInstance extends ConfigEntityBase implements \ArrayAccess, \Serializable {
34 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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  /**
   * 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.
   *
   * @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
   */
  public $description;

  /**
   * Field-type specific settings.
   *
   * An array of key/value pairs. The keys and default values are defined by the
   * field type in the 'instance_settings' entry of hook_field_info().
   *
   * @var array
   */
  public $settings;

  /**
   * 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
   */
  public $required;

  /**
   * 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
   */
  public $default_value;

  /**
   * 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
   */
  public $default_value_function;

  /**
   * The widget definition.
   *
   * An array of key/value pairs identifying the Form API input widget for
   * the field when used by this bundle.
   *   - type: (string) The plugin ID of the widget, such as text_textfield.
   *   - settings: (array) A sub-array of key/value pairs of settings. The keys
   *     and default values are defined by the widget plugin in the 'settings'
   *     entry of its "plugin definition" (typycally plugin class annotations).
   *   - weight: (float) The weight of the widget relative to the other
   *     elements in entity edit forms.
   *   - module: (string, read-only) The name of the module that provides the
   *     widget plugin.
   *
   * @var array
   */
  public $widget;

  /**
   * 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
   */
  public $deleted;

203 204 205 206 207 208 209
  /**
   * The field ConfigEntity object corresponding to $field_uuid.
   *
   * @var \Drupal\field\Plugin\Core\Entity\Field
   */
  protected $field;

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  /**
   * The widget plugin used for this instance.
   *
   * @var \Drupal\field\Plugin\Type\Widget\WidgetInterface
   */
  protected $widgetPlugin;

  /**
   * Flag indicating whether the bundle name can be renamed or not.
   *
   * @var bool
   */
  protected $bundle_rename_allowed = FALSE;

  /**
   * {@inheritdoc}
   */
  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']);
232 233
      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'])));
234
      }
235
      $values['field_uuid'] = $field->uuid;
236
    }
237 238 239 240 241
    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)));
242
      }
243
      if (!$field) {
244 245 246
        throw new FieldException(format_string('Attempt to create an instance of unknown field @uuid', array('@uuid' => $values['field_uuid'])));
      }
    }
247
    else {
248 249 250
      throw new FieldException('Attempt to create an instance of an unspecified field.');
    }

251 252 253 254 255 256 257 258 259 260 261 262 263
    // 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;

    // 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)));
    }

264 265
    // Provide defaults.
    $values += array(
266 267 268
      // 'Label' defaults to the field ID (mostly useful for field instances
      // created in tests).
      'label' => $this->field->id,
269 270 271 272 273 274
      'description' => '',
      'required' => FALSE,
      'default_value' => array(),
      'default_value_function' => '',
      'settings' => array(),
      'widget' => array(),
275
      'deleted' => FALSE,
276 277 278 279 280 281 282 283
    );
    parent::__construct($values, $entity_type);
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
284
    return $this->entity_type . '.' . $this->bundle . '.' . $this->field->id;
285 286 287 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 313 314 315 316 317 318 319 320 321 322 323
  }

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

  /**
   * {@inheritdoc}
   */
  public function save() {
    $module_handler = \Drupal::moduleHandler();
    $entity_manager = \Drupal::service('plugin.manager.entity');
    $instance_controller = $entity_manager->getStorageController($this->entityType);

    if ($this->isNew()) {
      // Check that the field can be attached to this entity type.
324 325
      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)));
326 327 328 329 330 331 332
      }

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

      // Ensure the field instance is unique within the bundle.
      if ($prior_instance = current($instance_controller->load(array($this->id)))) {
333
        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)));
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
      }

      $hook = 'field_create_instance';
      $hook_args = array($this);
    }
    // Otherwise, the field instance is being updated.
    else {
      $original = \Drupal::service('plugin.manager.entity')
        ->getStorageController($this->entityType)
        ->loadUnchanged($this->getOriginalID());

      // 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.");
      }
352
      if ($this->field_uuid != $original->field_uuid) {
353 354 355 356 357 358 359
        throw new FieldException("Cannot change an existing instance's field.");
      }

      $hook = 'field_update_instance';
      $hook_args = array($this, $original);
    }

360
    $field_type_info = field_info_field_types($this->field->type);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

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

    // Set the default widget and settings.
    $this->widget += array(
      'type' => $field_type_info['default_widget'],
      'settings' => array(),
    );
    // Get the widget module and settings from the widget type.
    if ($widget_type_info = \Drupal::service('plugin.manager.field.widget')->getDefinition($this->widget['type'])) {
      $this->widget['module'] = $widget_type_info['module'];
      $this->widget['settings'] += $widget_type_info['settings'];
    }
    // If no weight is specified, make sure the field sinks to the bottom.
    if (!isset($this->widget['weight'])) {
      $max_weight = field_info_max_weight($this->entity_type, $this->bundle, 'form');
      $this->widget['weight'] = isset($max_weight) ? $max_weight + 1 : 0;
    }

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

    // Invoke external hooks after the cache is cleared for API consistency.
    // This invokes hook_field_create_instance() or hook_field_update_instance()
    // depending on whether the field is new.
    $module_handler->invokeAll($hook, $hook_args);

    return $result;
  }

  /**
   * 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().
422
      $module_handler->invoke($this->field->storage['module'], 'field_storage_delete_instance', array($this));
423 424 425 426 427 428

      // Let modules react to the deletion of the instance with
      // hook_field_delete_instance().
      $module_handler->invokeAll('field_delete_instance', array($this));

      // Delete the field itself if we just deleted its last instance.
429 430
      if ($field_cleanup && count($this->field->getBundles()) == 0) {
        $this->field->delete();
431 432 433 434
      }
    }
  }

435 436 437 438 439 440 441 442 443 444
 /**
  * Returns the field entity for this instance.
  *
  * @return \Drupal\field\Plugin\Core\Entity\Field
  *   The field entity for this instance.
  */
  public function getField() {
    return $this->field;
  }

445 446 447 448 449 450 451 452 453 454 455 456 457 458
  /**
   * Returns the Widget plugin for the instance.
   *
   * @return Drupal\field\Plugin\Type\Widget\WidgetInterface
   *   The Widget plugin to be used for the instance.
   */
  public function getWidget() {
    if (empty($this->widgetPlugin)) {
      $widget_properties = $this->widget;

      // Let modules alter the widget properties.
      $context = array(
        'entity_type' => $this->entity_type,
        'bundle' => $this->bundle,
459
        'field' => $this->field,
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
        'instance' => $this,
      );
      // Invoke hook_field_widget_properties_alter() and
      // hook_field_widget_properties_ENTITY_TYPE_alter().
      drupal_alter(array('field_widget_properties', 'field_widget_properties_' . $this->entity_type), $widget_properties, $context);

      $options = array(
        'instance' => $this,
        'type' => $widget_properties['type'],
        'settings' => $widget_properties['settings'],
        'weight' => $widget_properties['weight'],
      );
      $this->widgetPlugin = \Drupal::service('plugin.manager.field.widget')->getInstance($options);
    }

    return $this->widgetPlugin;
  }

  /**
   * Allows a bundle to be renamed.
   *
   * Renaming a bundle on the instance is allowed when an entity's bundle
   * is renamed and when field_entity_bundle_rename() does internal
   * housekeeping.
   */
  public function allowBundleRename() {
    $this->bundle_rename_allowed = TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function offsetExists($offset) {
493
    return (isset($this->{$offset}) || $offset == 'field_id' || $offset == 'field_name');
494 495 496 497 498 499 500 501 502
  }

  /**
   * {@inheritdoc}
   */
  public function &offsetGet($offset) {
    if ($offset == 'field_id') {
      return $this->field_uuid;
    }
503 504 505
    if ($offset == 'field_name') {
      return $this->field->id;
    }
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    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});
  }

529 530 531 532 533 534 535 536 537 538 539 540 541 542
  /**
   * {@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));
  }
543

544
}