class FieldItemList in Drupal 9
Same name and namespace in other branches
- 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
- class \Drupal\Core\TypedData\TypedData implements PluginInspectionInterface, TypedDataInterface uses DependencySerializationTrait, StringTranslationTrait, TypedDataTrait
- class \Drupal\Core\TypedData\Plugin\DataType\ItemList implements \Drupal\Core\TypedData\Plugin\DataType\IteratorAggregate, ListInterface
- class \Drupal\Core\Field\FieldItemList implements FieldItemListInterface
- class \Drupal\Core\TypedData\Plugin\DataType\ItemList implements \Drupal\Core\TypedData\Plugin\DataType\IteratorAggregate, ListInterface
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
File
- core/
lib/ Drupal/ Core/ Field/ FieldItemList.php, line 21
Namespace
Drupal\Core\FieldView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
FieldItemList:: |
protected | property | The langcode of the field values held in the object. | |
FieldItemList:: |
protected | property |
Numerically indexed array of field items. Overrides ItemList:: |
1 |
FieldItemList:: |
public | function |
Checks data value access. Overrides AccessibleInterface:: |
1 |
FieldItemList:: |
public | function |
Applies the default value. Overrides TypedData:: |
|
FieldItemList:: |
protected | function |
Helper for creating a list item object. Overrides ItemList:: |
|
FieldItemList:: |
public | function |
Contains the default access logic of this field. Overrides FieldItemListInterface:: |
3 |
FieldItemList:: |
public | function |
Returns a form for the default value input. Overrides FieldItemListInterface:: |
2 |
FieldItemList:: |
public | function |
Processes the submitted default value. Overrides FieldItemListInterface:: |
2 |
FieldItemList:: |
public | function |
Validates the submitted default value. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
protected | function | Returns the widget object used in default value form. | |
FieldItemList:: |
protected | function | Calls a method on each FieldItem. | |
FieldItemList:: |
public | function |
Defines custom delete behavior for field values. Overrides FieldItemListInterface:: |
2 |
FieldItemList:: |
public | function |
Defines custom revision delete behavior for field values. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
public | function |
Determines equality to another object implementing FieldItemListInterface. Overrides FieldItemListInterface:: |
2 |
FieldItemList:: |
public | function |
Filters out empty field items and re-numbers the item deltas. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Populates a specified number of field items with valid sample data. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
public | function |
Gets a list of validation constraints. Overrides TypedData:: |
1 |
FieldItemList:: |
public | function |
Gets the entity that field belongs to. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
public | function |
Gets the field definition. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Gets the langcode of the field values held in the object. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Returns the value of a given field setting. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Returns the array of field settings. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Determines whether the field has relevant changes. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
public | function |
Defines custom post-save behavior for field values. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
public | function |
Defines custom presave behavior for field values. Overrides FieldItemListInterface:: |
1 |
FieldItemList:: |
public static | function |
Processes the default value before being applied. Overrides FieldItemListInterface:: |
2 |
FieldItemList:: |
public | function |
Sets the langcode of the field values held in the object. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Sets the data value. Overrides ItemList:: |
|
FieldItemList:: |
public | function |
Returns a renderable array for the field items. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Magic method: Gets a property value of to the first field item. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Magic method: Determines whether a property of the first field item is set. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Magic method: Sets a property value of the first field item. Overrides FieldItemListInterface:: |
|
FieldItemList:: |
public | function |
Magic method: Unsets a property of the first field item. Overrides FieldItemListInterface:: |
|
ItemList:: |
public | function |
Appends a new item to the list. Overrides ListInterface:: |
|
ItemList:: |
public | function | ||
ItemList:: |
public | function |
Filters the items in the list using a custom callback. Overrides ListInterface:: |
|
ItemList:: |
public | function |
Returns the first item in this list. Overrides ListInterface:: |
|
ItemList:: |
public | function |
Returns the item at the specified position in this list. Overrides ListInterface:: |
2 |
ItemList:: |
public | function |
Gets the definition of a contained item. Overrides ListInterface:: |
|
ItemList:: |
public | function | ||
ItemList:: |
public | function |
Returns a string representation of the data. Overrides TypedData:: |
|
ItemList:: |
public | function |
Gets the data value. Overrides TypedData:: |
|
ItemList:: |
public | function |
Determines whether the list contains any non-empty items. Overrides ListInterface:: |
|
ItemList:: |
public | function | 1 | |
ItemList:: |
public | function | ||
ItemList:: |
public | function | ||
ItemList:: |
public | function | ||
ItemList:: |
public | function |
React to changes to a child property or item. Overrides TraversableTypedDataInterface:: |
1 |
ItemList:: |
protected | function | Renumbers the items in the list. | |
ItemList:: |
public | function |
Removes the item at the specified position. Overrides ListInterface:: |
|
ItemList:: |
public | function |
Sets the value of the item at a given position in the list. Overrides ListInterface:: |
|
ItemList:: |
public | function | Magic method: Implements a deep clone. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
TypedData:: |
protected | property | The data definition. | 1 |
TypedData:: |
protected | property | The property name. | |
TypedData:: |
protected | property | The parent typed data object. | |
TypedData:: |
public static | function |
Constructs a TypedData object given its definition and context. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Gets the data definition. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Returns the name of a property or item. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Returns the parent data structure; i.e. either complex data or a list. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
|
TypedData:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
TypedData:: |
public | function |
Returns the property path of the data. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Returns the root of the typed data tree. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Sets the context of a property or item via a context aware parent. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function |
Validates the currently set data value. Overrides TypedDataInterface:: |
|
TypedData:: |
public | function | Constructs a TypedData object given its definition and context. | 3 |
TypedDataTrait:: |
protected | property | The typed data manager used for creating the data types. | |
TypedDataTrait:: |
public | function | Gets the typed data manager. | 2 |
TypedDataTrait:: |
public | function | Sets the typed data manager. | 2 |