You are here

class FieldItemList in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/FieldItemList.php \Drupal\Core\Field\FieldItemList

Represents an entity field; that is, a list of field item objects.

An entity field is a list of field items, each containing a set of properties. Note that even single-valued entity fields are represented as list of field items, however for easy access to the contained item the entity field delegates __get() and __set() calls directly to the first item.

Hierarchy

Expanded class hierarchy of FieldItemList

11 files declare their use of FieldItemList
BaseFieldOverrideTest.php in core/tests/Drupal/KernelTests/Core/Field/Entity/BaseFieldOverrideTest.php
CommentFieldItemList.php in core/modules/comment/src/CommentFieldItemList.php
ComputedTestCacheableStringItemList.php in core/modules/system/tests/modules/entity_test/src/Plugin/Field/ComputedTestCacheableStringItemList.php
ComputedTestFieldItemList.php in core/modules/system/tests/modules/entity_test/src/Plugin/Field/ComputedTestFieldItemList.php
DateRangeFieldItemList.php in core/modules/datetime_range/src/Plugin/Field/FieldType/DateRangeFieldItemList.php

... See full list

File

core/lib/Drupal/Core/Field/FieldItemList.php, line 21

Namespace

Drupal\Core\Field
View source
class FieldItemList extends ItemList implements FieldItemListInterface {

  /**
   * Numerically indexed array of field items.
   *
   * @var \Drupal\Core\Field\FieldItemInterface[]
   */
  protected $list = [];

  /**
   * The langcode of the field values held in the object.
   *
   * @var string
   */
  protected $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;

  /**
   * {@inheritdoc}
   */
  protected function createItem($offset = 0, $value = NULL) {
    return \Drupal::service('plugin.manager.field.field_type')
      ->createFieldItem($this, $offset, $value);
  }

  /**
   * {@inheritdoc}
   */
  public function getEntity() {

    // The "parent" is the TypedData object for the entity, we need to unwrap
    // the actual entity.
    return $this
      ->getParent()
      ->getValue();
  }

  /**
   * {@inheritdoc}
   */
  public function setLangcode($langcode) {
    $this->langcode = $langcode;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function getSetting($setting_name) {
    return $this->definition
      ->getSetting($setting_name);
  }

  /**
   * {@inheritdoc}
   */
  public function filterEmptyItems() {
    $this
      ->filter(function ($item) {
      return !$item
        ->isEmpty();
    });
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($values, $notify = TRUE) {

    // Support passing in only the value of the first item, either as a literal
    // (value of the first property) or as an array of properties.
    if (isset($values) && (!is_array($values) || !empty($values) && !is_numeric(current(array_keys($values))))) {
      $values = [
        0 => $values,
      ];
    }
    parent::setValue($values, $notify);
  }

  /**
   * {@inheritdoc}
   */
  public function __get($property_name) {

    // For empty fields, $entity->field->property is NULL.
    if ($item = $this
      ->first()) {
      return $item
        ->__get($property_name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function __set($property_name, $value) {

    // For empty fields, $entity->field->property = $value automatically
    // creates the item before assigning the value.
    $item = $this
      ->first() ?: $this
      ->appendItem();
    $item
      ->__set($property_name, $value);
  }

  /**
   * {@inheritdoc}
   */
  public function __isset($property_name) {
    if ($item = $this
      ->first()) {
      return $item
        ->__isset($property_name);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function __unset($property_name) {
    if ($item = $this
      ->first()) {
      $item
        ->__unset($property_name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    $access_control_handler = \Drupal::entityTypeManager()
      ->getAccessControlHandler($this
      ->getEntity()
      ->getEntityTypeId());
    return $access_control_handler
      ->fieldAccess($operation, $this
      ->getFieldDefinition(), $account, $this, $return_as_object);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultAccess($operation = 'view', AccountInterface $account = NULL) {

    // Grant access per default.
    return AccessResult::allowed();
  }

  /**
   * {@inheritdoc}
   */
  public function applyDefaultValue($notify = TRUE) {
    if ($value = $this
      ->getFieldDefinition()
      ->getDefaultValue($this
      ->getEntity())) {
      $this
        ->setValue($value, $notify);
    }
    else {

      // Create one field item and give it a chance to apply its defaults.
      // Remove it if this ended up doing nothing.
      // @todo Having to create an item in case it wants to set a value is
      // absurd. Remove that in https://www.drupal.org/node/2356623.
      $item = $this
        ->first() ?: $this
        ->appendItem();
      $item
        ->applyDefaultValue(FALSE);
      $this
        ->filterEmptyItems();
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function preSave() {

    // Filter out empty items.
    $this
      ->filterEmptyItems();
    $this
      ->delegateMethod('preSave');
  }

  /**
   * {@inheritdoc}
   */
  public function postSave($update) {
    $result = $this
      ->delegateMethod('postSave', $update);
    return (bool) array_filter($result);
  }

  /**
   * {@inheritdoc}
   */
  public function delete() {
    $this
      ->delegateMethod('delete');
  }

  /**
   * {@inheritdoc}
   */
  public function deleteRevision() {
    $this
      ->delegateMethod('deleteRevision');
  }

  /**
   * Calls a method on each FieldItem.
   *
   * Any argument passed will be forwarded to the invoked method.
   *
   * @param string $method
   *   The name of the method to be invoked.
   *
   * @return array
   *   An array of results keyed by delta.
   */
  protected function delegateMethod($method) {
    $result = [];
    $args = array_slice(func_get_args(), 1);
    foreach ($this->list as $delta => $item) {

      // call_user_func_array() is way slower than a direct call so we avoid
      // using it if have no parameters.
      $result[$delta] = $args ? call_user_func_array([
        $item,
        $method,
      ], $args) : $item
        ->{$method}();
    }
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function view($display_options = []) {
    $view_builder = \Drupal::entityTypeManager()
      ->getViewBuilder($this
      ->getEntity()
      ->getEntityTypeId());
    return $view_builder
      ->viewField($this, $display_options);
  }

  /**
   * {@inheritdoc}
   */
  public function generateSampleItems($count = 1) {
    $field_definition = $this
      ->getFieldDefinition();
    $field_type_class = $field_definition
      ->getItemDefinition()
      ->getClass();
    for ($delta = 0; $delta < $count; $delta++) {
      $values[$delta] = $field_type_class::generateSampleValue($field_definition);
    }
    $this
      ->setValue($values);
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

    // Check that the number of values doesn't exceed the field cardinality. For
    // form submitted values, this can only happen with 'multiple value'
    // widgets.
    $cardinality = $this
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getCardinality();
    if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
      $constraints[] = $this
        ->getTypedDataManager()
        ->getValidationConstraintManager()
        ->create('Count', [
        'max' => $cardinality,
        'maxMessage' => t('%name: this field cannot hold more than @count values.', [
          '%name' => $this
            ->getFieldDefinition()
            ->getLabel(),
          '@count' => $cardinality,
        ]),
      ]);
    }
    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
    if (empty($this
      ->getFieldDefinition()
      ->getDefaultValueCallback())) {
      if ($widget = $this
        ->defaultValueWidget($form_state)) {

        // Place the input in a separate place in the submitted values tree.
        $element = [
          '#parents' => [
            'default_value_input',
          ],
        ];
        $element += $widget
          ->form($this, $element, $form_state);
        return $element;
      }
      else {
        return [
          '#markup' => $this
            ->t('No widget available for: %type.', [
            '%type' => $this
              ->getFieldDefinition()
              ->getType(),
          ]),
        ];
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state) {

    // Extract the submitted value, and validate it.
    if ($widget = $this
      ->defaultValueWidget($form_state)) {
      $widget
        ->extractFormValues($this, $element, $form_state);

      // Force a non-required field definition.
      // @see self::defaultValueWidget().
      $this
        ->getFieldDefinition()
        ->setRequired(FALSE);
      $violations = $this
        ->validate();

      // Assign reported errors to the correct form element.
      if (count($violations)) {
        $widget
          ->flagErrors($this, $violations, $element, $form_state);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function defaultValuesFormSubmit(array $element, array &$form, FormStateInterface $form_state) {

    // Extract the submitted value, and return it as an array.
    if ($widget = $this
      ->defaultValueWidget($form_state)) {
      $widget
        ->extractFormValues($this, $element, $form_state);
      return $this
        ->getValue();
    }
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
    return $default_value;
  }

  /**
   * Returns the widget object used in default value form.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state of the (entire) configuration form.
   *
   * @return \Drupal\Core\Field\WidgetInterface|null
   *   A Widget object or NULL if no widget is available.
   */
  protected function defaultValueWidget(FormStateInterface $form_state) {
    if (!$form_state
      ->has('default_value_widget')) {
      $entity = $this
        ->getEntity();

      // Force a non-required widget.
      $definition = $this
        ->getFieldDefinition();
      $definition
        ->setRequired(FALSE);
      $definition
        ->setDescription('');

      // Use the widget currently configured for the 'default' form mode, or
      // fallback to the default widget for the field type.
      $entity_form_display = \Drupal::service('entity_display.repository')
        ->getFormDisplay($entity
        ->getEntityTypeId(), $entity
        ->bundle());
      $widget = $entity_form_display
        ->getRenderer($this
        ->getFieldDefinition()
        ->getName());
      if (!$widget) {
        $widget = \Drupal::service('plugin.manager.field.widget')
          ->getInstance([
          'field_definition' => $this
            ->getFieldDefinition(),
        ]);
      }
      $form_state
        ->set('default_value_widget', $widget);
    }
    return $form_state
      ->get('default_value_widget');
  }

  /**
   * {@inheritdoc}
   */
  public function equals(FieldItemListInterface $list_to_compare) {
    $count1 = count($this);
    $count2 = count($list_to_compare);
    if ($count1 === 0 && $count2 === 0) {

      // Both are empty we can safely assume that it did not change.
      return TRUE;
    }
    if ($count1 !== $count2) {

      // One of them is empty but not the other one so the value changed.
      return FALSE;
    }
    $value1 = $this
      ->getValue();
    $value2 = $list_to_compare
      ->getValue();
    if ($value1 === $value2) {
      return TRUE;
    }

    // If the values are not equal ensure a consistent order of field item
    // properties and remove properties which will not be saved.
    $property_definitions = $this
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getPropertyDefinitions();
    $non_computed_properties = array_filter($property_definitions, function (DataDefinitionInterface $property) {
      return !$property
        ->isComputed();
    });
    $callback = function (&$value) use ($non_computed_properties) {
      if (is_array($value)) {
        $value = array_intersect_key($value, $non_computed_properties);

        // Also filter out properties with a NULL value as they might exist in
        // one field item and not in the other, depending on how the values are
        // set. Do not filter out empty strings or other false-y values as e.g.
        // a NULL or FALSE in a boolean field is not the same.
        $value = array_filter($value, function ($property) {
          return $property !== NULL;
        });
        ksort($value);
      }
    };
    array_walk($value1, $callback);
    array_walk($value2, $callback);
    return $value1 == $value2;
  }

  /**
   * {@inheritdoc}
   */
  public function hasAffectingChanges(FieldItemListInterface $original_items, $langcode) {
    return !$this
      ->equals($original_items);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FieldItemList::$langcode protected property The langcode of the field values held in the object.
FieldItemList::$list protected property Numerically indexed array of field items. Overrides ItemList::$list 1
FieldItemList::access public function Checks data value access. Overrides AccessibleInterface::access 1
FieldItemList::applyDefaultValue public function Applies the default value. Overrides TypedData::applyDefaultValue
FieldItemList::createItem protected function Helper for creating a list item object. Overrides ItemList::createItem
FieldItemList::defaultAccess public function Contains the default access logic of this field. Overrides FieldItemListInterface::defaultAccess 3
FieldItemList::defaultValuesForm public function Returns a form for the default value input. Overrides FieldItemListInterface::defaultValuesForm 2
FieldItemList::defaultValuesFormSubmit public function Processes the submitted default value. Overrides FieldItemListInterface::defaultValuesFormSubmit 2
FieldItemList::defaultValuesFormValidate public function Validates the submitted default value. Overrides FieldItemListInterface::defaultValuesFormValidate 1
FieldItemList::defaultValueWidget protected function Returns the widget object used in default value form.
FieldItemList::delegateMethod protected function Calls a method on each FieldItem.
FieldItemList::delete public function Defines custom delete behavior for field values. Overrides FieldItemListInterface::delete 2
FieldItemList::deleteRevision public function Defines custom revision delete behavior for field values. Overrides FieldItemListInterface::deleteRevision 1
FieldItemList::equals public function Determines equality to another object implementing FieldItemListInterface. Overrides FieldItemListInterface::equals 2
FieldItemList::filterEmptyItems public function Filters out empty field items and re-numbers the item deltas. Overrides FieldItemListInterface::filterEmptyItems
FieldItemList::generateSampleItems public function Populates a specified number of field items with valid sample data. Overrides FieldItemListInterface::generateSampleItems 1
FieldItemList::getConstraints public function Gets a list of validation constraints. Overrides TypedData::getConstraints 1
FieldItemList::getEntity public function Gets the entity that field belongs to. Overrides FieldItemListInterface::getEntity 1
FieldItemList::getFieldDefinition public function Gets the field definition. Overrides FieldItemListInterface::getFieldDefinition
FieldItemList::getLangcode public function Gets the langcode of the field values held in the object. Overrides FieldItemListInterface::getLangcode
FieldItemList::getSetting public function Returns the value of a given field setting. Overrides FieldItemListInterface::getSetting
FieldItemList::getSettings public function Returns the array of field settings. Overrides FieldItemListInterface::getSettings
FieldItemList::hasAffectingChanges public function Determines whether the field has relevant changes. Overrides FieldItemListInterface::hasAffectingChanges 1
FieldItemList::postSave public function Defines custom post-save behavior for field values. Overrides FieldItemListInterface::postSave 1
FieldItemList::preSave public function Defines custom presave behavior for field values. Overrides FieldItemListInterface::preSave 1
FieldItemList::processDefaultValue public static function Processes the default value before being applied. Overrides FieldItemListInterface::processDefaultValue 2
FieldItemList::setLangcode public function Sets the langcode of the field values held in the object. Overrides FieldItemListInterface::setLangcode
FieldItemList::setValue public function Sets the data value. Overrides ItemList::setValue
FieldItemList::view public function Returns a renderable array for the field items. Overrides FieldItemListInterface::view
FieldItemList::__get public function Magic method: Gets a property value of to the first field item. Overrides FieldItemListInterface::__get
FieldItemList::__isset public function Magic method: Determines whether a property of the first field item is set. Overrides FieldItemListInterface::__isset
FieldItemList::__set public function Magic method: Sets a property value of the first field item. Overrides FieldItemListInterface::__set
FieldItemList::__unset public function Magic method: Unsets a property of the first field item. Overrides FieldItemListInterface::__unset
ItemList::appendItem public function Appends a new item to the list. Overrides ListInterface::appendItem
ItemList::count public function
ItemList::filter public function Filters the items in the list using a custom callback. Overrides ListInterface::filter
ItemList::first public function Returns the first item in this list. Overrides ListInterface::first
ItemList::get public function Returns the item at the specified position in this list. Overrides ListInterface::get 2
ItemList::getItemDefinition public function Gets the definition of a contained item. Overrides ListInterface::getItemDefinition
ItemList::getIterator public function
ItemList::getString public function Returns a string representation of the data. Overrides TypedData::getString
ItemList::getValue public function Gets the data value. Overrides TypedData::getValue
ItemList::isEmpty public function Determines whether the list contains any non-empty items. Overrides ListInterface::isEmpty
ItemList::offsetExists public function 1
ItemList::offsetGet public function
ItemList::offsetSet public function
ItemList::offsetUnset public function
ItemList::onChange public function React to changes to a child property or item. Overrides TraversableTypedDataInterface::onChange 1
ItemList::rekey protected function Renumbers the items in the list.
ItemList::removeItem public function Removes the item at the specified position. Overrides ListInterface::removeItem
ItemList::set public function Sets the value of the item at a given position in the list. Overrides ListInterface::set
ItemList::__clone public function Magic method: Implements a deep clone.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TypedData::$definition protected property The data definition. 1
TypedData::$name protected property The property name.
TypedData::$parent protected property The parent typed data object.
TypedData::createInstance public static function Constructs a TypedData object given its definition and context. Overrides TypedDataInterface::createInstance
TypedData::getDataDefinition public function Gets the data definition. Overrides TypedDataInterface::getDataDefinition
TypedData::getName public function Returns the name of a property or item. Overrides TypedDataInterface::getName
TypedData::getParent public function Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface::getParent
TypedData::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
TypedData::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
TypedData::getPropertyPath public function Returns the property path of the data. Overrides TypedDataInterface::getPropertyPath
TypedData::getRoot public function Returns the root of the typed data tree. Overrides TypedDataInterface::getRoot
TypedData::setContext public function Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface::setContext
TypedData::validate public function Validates the currently set data value. Overrides TypedDataInterface::validate
TypedData::__construct public function Constructs a TypedData object given its definition and context. 3
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2