You are here

public function ItemList::setValue in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/TypedData/Plugin/DataType/ItemList.php \Drupal\Core\TypedData\Plugin\DataType\ItemList::setValue()

Overrides \Drupal\Core\TypedData\TypedData::setValue().

Parameters

array|null $values: An array of values of the field items, or NULL to unset the field.

bool $notify: (optional) Whether to notify the parent object of the change. Defaults to TRUE.

Overrides TypedData::setValue

1 call to ItemList::setValue()
FieldItemList::setValue in core/lib/Drupal/Core/Field/FieldItemList.php
Sets the data value.
1 method overrides ItemList::setValue()
FieldItemList::setValue in core/lib/Drupal/Core/Field/FieldItemList.php
Sets the data value.

File

core/lib/Drupal/Core/TypedData/Plugin/DataType/ItemList.php, line 55

Class

ItemList
A generic list class.

Namespace

Drupal\Core\TypedData\Plugin\DataType

Code

public function setValue($values, $notify = TRUE) {
  if (!isset($values) || $values === []) {
    $this->list = [];
  }
  else {

    // Only arrays with numeric keys are supported.
    if (!is_array($values)) {
      throw new \InvalidArgumentException('Cannot set a list with a non-array value.');
    }

    // Assign incoming values. Keys are renumbered to ensure 0-based
    // sequential deltas. If possible, reuse existing items rather than
    // creating new ones.
    foreach (array_values($values) as $delta => $value) {
      if (!isset($this->list[$delta])) {
        $this->list[$delta] = $this
          ->createItem($delta, $value);
      }
      else {
        $this->list[$delta]
          ->setValue($value, FALSE);
      }
    }

    // Truncate extraneous pre-existing values.
    $this->list = array_slice($this->list, 0, count($values));
  }

  // Notify the parent of any changes.
  if ($notify && isset($this->parent)) {
    $this->parent
      ->onChange($this->name);
  }
}