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

/**
 * @file
 * Contains \Drupal\Core\Field\FieldConfigBase.
 */

namespace Drupal\Core\Field;

10
use Drupal\Component\Plugin\DependentPluginInterface;
11
use Drupal\Core\Config\Entity\ConfigEntityBase;
12
use Drupal\Core\Config\Entity\ThirdPartySettingsTrait;
13
use Drupal\Core\Entity\EntityStorageInterface;
14
use Drupal\Core\Entity\FieldableEntityInterface;
15
use Drupal\Core\Field\TypedData\FieldItemDataDefinition;
16
use Drupal\Component\Utility\String;
17 18 19 20 21 22

/**
 * Base class for configurable field definitions.
 */
abstract class FieldConfigBase extends ConfigEntityBase implements FieldConfigInterface {

23 24
  use ThirdPartySettingsTrait;

25
  /**
26
   * The field ID.
27 28 29 30 31 32 33 34 35 36
   *
   * 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;

  /**
37
   * The name of the field attached to the bundle by this field.
38 39 40 41 42
   *
   * @var string
   */
  public $field_name;

43 44 45 46 47 48 49 50 51 52 53 54 55
  /**
   * The field type.
   *
   * This property is denormalized from the field storage for optimization of
   * the "entity and render cache hits" critical paths. If not present in the
   * $values passed to create(), it is populated from the field storage in
   * postCreate(), and saved in config records so that it is present on
   * subsequent loads.
   *
   * @var string
   */
  public $field_type;

56
  /**
57
   * The name of the entity type the field is attached to.
58 59 60 61 62 63
   *
   * @var string
   */
  public $entity_type;

  /**
64
   * The name of the bundle the field is attached to.
65 66 67 68 69 70
   *
   * @var string
   */
  public $bundle;

  /**
71
   * The human-readable label for the field.
72 73 74 75
   *
   * 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.
   *
76 77
   * If not specified, this defaults to the field_name (mostly useful for fields
   * created in tests).
78 79 80 81 82 83
   *
   * @var string
   */
  public $label;

  /**
84
   * The field description.
85 86 87
   *
   * 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
88
   * this field in entity edit forms.
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
   *
   * @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.
   *
   * @var array
   */
  public $settings = array();

  /**
   * 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 = FALSE;

  /**
   * Flag indicating whether the field is translatable.
   *
   * Defaults to TRUE.
   *
   * @var bool
   */
  public $translatable = TRUE;

  /**
   * 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.
   *
140
   * This property is overlooked if the $default_value_callback is non-empty.
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
   *
   * Example for a integer field:
   * @code
   * array(
   *   array('value' => 1),
   *   array('value' => 2),
   * )
   * @endcode
   *
   * @var array
   */
  public $default_value = array();

  /**
   * The name of a callback function that returns default values.
   *
   * The function will be called with the following arguments:
158
   * - \Drupal\Core\Entity\FieldableEntityInterface $entity
159 160 161 162 163 164 165 166 167 168 169
   *   The entity being created.
   * - \Drupal\Core\Field\FieldDefinitionInterface $definition
   *   The field definition.
   * 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
   */
170
  public $default_value_callback = '';
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

  /**
   * The field storage object.
   *
   * @var \Drupal\Core\Field\FieldStorageDefinitionInterface
   */
  protected $fieldStorage;

  /**
   * The data definition of a field item.
   *
   * @var \Drupal\Core\Field\TypedData\FieldItemDataDefinition
   */
  protected $itemDefinition;

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

193 194 195 196 197 198 199
  /**
   * Array of constraint options keyed by constraint plugin ID.
   *
   * @var array
   */
  protected $constraints = [];

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  /**
   * {@inheritdoc}
   */
  public function id() {
    return $this->entity_type . '.' . $this->bundle . '.' . $this->field_name;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getType() {
218
    return $this->field_type;
219 220 221 222 223 224 225 226 227 228 229 230
  }

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

  /**
   * {@inheritdoc}
   */
231
  public function getTargetBundle() {
232 233 234 235 236 237 238 239
    return $this->bundle;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    // Add dependencies from the field type plugin. We can not use
    // self::calculatePluginDependencies() because instantiation of a field item
    // plugin requires a parent entity.
    /** @var $field_type_manager \Drupal\Core\Field\FieldTypePluginManagerInterface */
    $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
    $definition = $field_type_manager->getDefinition($this->getType());
    $this->addDependency('module', $definition['provider']);
    // Plugins can declare additional dependencies in their definition.
    if (isset($definition['config_dependencies'])) {
      $this->addDependencies($definition['config_dependencies']);
    }
    // Let the field type plugin specify its own dependencies.
    // @see \Drupal\Core\Field\FieldItemInterface::calculateDependencies()
    $this->addDependencies($definition['class']::calculateDependencies($this));

    // If the target entity type uses entities to manage its bundles then
    // depend on the bundle entity.
257 258
    $bundle_entity_type_id = $this->entityManager()->getDefinition($this->entity_type)->getBundleEntityType();
    if ($bundle_entity_type_id != 'bundle') {
259
      if (!$bundle_entity = $this->entityManager()->getStorage($bundle_entity_type_id)->load($this->bundle)) {
260
        throw new \LogicException(String::format('Missing bundle entity, entity type %type, entity id %bundle.', array('%type' => $bundle_entity_type_id, '%bundle' => $this->bundle)));
261
      }
262
      $this->addDependency('config', $bundle_entity->getConfigDependencyName());
263 264 265 266
    }
    return $this->dependencies;
  }

267 268 269 270 271 272 273 274 275 276 277 278 279
  /**
   * {@inheritdoc}
   */
  public function postCreate(EntityStorageInterface $storage) {
    parent::postCreate($storage);
    // If it was not present in the $values passed to create(), (e.g. for
    // programmatic creation), populate the denormalized field_type property
    // from the field storage, so that it gets saved in the config record.
    if (empty($this->field_type)) {
      $this->field_type = $this->getFieldStorageDefinition()->getType();
    }
  }

280 281 282 283 284 285 286 287 288
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    // Clear the cache.
    $this->entityManager()->clearCachedFieldDefinitions();

    // Invalidate the render cache for all affected entities.
    $entity_type = $this->getFieldStorageDefinition()->getTargetEntityTypeId();
289
    if ($this->entityManager()->hasHandler($entity_type, 'view_builder')) {
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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
      $this->entityManager()->getViewBuilder($entity_type)->resetCache();
    }
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function isTranslatable() {
    // A field can be enabled for translation only if translation is supported.
    return $this->translatable && $this->getFieldStorageDefinition()->isTranslatable();
  }

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

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

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

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

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

  /**
   * {@inheritdoc}
   */
361
  public function getDefaultValue(FieldableEntityInterface $entity) {
362
    // Allow custom default values function.
363 364
    if ($callback = $this->default_value_callback) {
      $value = call_user_func($callback, $entity, $this);
365 366 367 368
    }
    else {
      $value = $this->default_value;
    }
369 370 371 372 373 374 375 376
    // Normalize into the "array keyed by delta" format.
    if (isset($value) && !is_array($value)) {
      $properties = $this->getFieldStorageDefinition()->getPropertyNames();
      $property = reset($properties);
      $value = array(
        array($property => $value),
      );
    }
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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    // Allow the field type to process default values.
    $field_item_list_class = $this->getClass();
    return $field_item_list_class::processDefaultValue($value, $entity, $this);
  }

  /**
   * Implements the magic __sleep() method.
   *
   * Using the Serialize interface and serialize() / unserialize() methods
   * breaks entity forms in PHP 5.4.
   * @todo Investigate in https://drupal.org/node/2074253.
   */
  public function __sleep() {
    // Only serialize necessary properties, excluding those that can be
    // recalculated.
    $properties = get_object_vars($this);
    unset($properties['fieldStorage'], $properties['itemDefinition'], $properties['bundleRenameAllowed']);
    return array_keys($properties);
  }

  /**
   * {@inheritdoc}
   */
  public static function createFromItemType($item_type) {
    // Forward to the field definition class for creating new data definitions
    // via the typed manager.
    return BaseFieldDefinition::createFromItemType($item_type);
  }

  /**
   * {@inheritdoc}
   */
  public static function createFromDataType($type) {
    // Forward to the field definition class for creating new data definitions
    // via the typed manager.
    return BaseFieldDefinition::createFromDataType($type);
  }

  public function getDataType() {
    return 'list';
  }

  /**
   * {@inheritdoc}
   */
  public function isList() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getClass() {
    // Derive list class from the field type.
    $type_definition = \Drupal::service('plugin.manager.field.field_type')
      ->getDefinition($this->getType());
    return $type_definition['list_class'];
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
440
    return \Drupal::typedDataManager()->getDefaultConstraints($this) + $this->constraints;
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 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
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraint($constraint_name) {
    $constraints = $this->getConstraints();
    return isset($constraints[$constraint_name]) ? $constraints[$constraint_name] : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemDefinition() {
    if (!isset($this->itemDefinition)) {
      $this->itemDefinition = FieldItemDataDefinition::create($this)
        ->setSettings($this->getSettings());
    }
    return $this->itemDefinition;
  }

  /**
   * {@inheritdoc}
   */
  public function setDefaultValue($value) {
    if (!is_array($value)) {
      $key = $this->getFieldStorageDefinition()->getPropertyNames()[0];
      // Convert to the multi value format to support fields with a cardinality
      // greater than 1.
      $value = array(
        array($key => $value),
      );
    }
    $this->default_value = $value;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function allowBundleRename() {
    $this->bundleRenameAllowed = TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig($bundle) {
    return $this;
  }

492 493 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
  /**
   * {@inheritdoc}
   */
  public function setConstraints(array $constraints) {
    $this->constraints = $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public function addConstraint($constraint_name, $options = NULL) {
    $this->constraints[$constraint_name] = $options;
  }

  /**
   * {@inheritdoc}
   */
  public function setPropertyConstraints($name, array $constraints) {
    $item_constraints = $this->getItemDefinition()->getConstraints();
    $item_constraints['ComplexData'][$name] = $constraints;
    $this->getItemDefinition()->setConstraints($item_constraints);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function addPropertyConstraints($name, array $constraints) {
    $item_constraints = $this->getItemDefinition()->getConstraint('ComplexData') ?: [];
    if (isset($item_constraints[$name])) {
      // Add the new property constraints, overwriting as required.
      $item_constraints[$name] = $constraints + $item_constraints[$name];
    }
    else {
      $item_constraints[$name] = $constraints;
    }
    $this->getItemDefinition()->addConstraint('ComplexData', $item_constraints);
    return $this;
  }

532
}