public function Field::setValue

Implements TypedDataInterface::setValue().

Parameters

array $values: An array of values of the field items.

Overrides TypedData::setValue

File

drupal/core/lib/Drupal/Core/Entity/Field/Type/Field.php, line 70
Definition of Drupal\Core\Entity\Field\Type\Field.

Class

Field
An entity field, i.e. a list of field items.

Namespace

Drupal\Core\Entity\Field\Type

Code

public function setValue($values) {
  if (isset($values) && $values !== array()) {

    // Support passing in only the value of the first item.
    if (!is_array($values) || !is_numeric(current(array_keys($values)))) {
      $values = array(
        0 => $values,
      );
    }
    if (!is_array($values)) {
      throw new InvalidArgumentException("An entity field requires a numerically indexed array of items as value.");
    }

    // Clear the values of properties for which no value has been passed.
    foreach (array_diff_key($this->list, $values) as $delta => $item) {
      unset($this->list[$delta]);
    }

    // Set the values.
    foreach ($values as $delta => $value) {
      if (!is_numeric($delta)) {
        throw new InvalidArgumentException('Unable to set a value with a non-numeric delta in a list.');
      }
      elseif (!isset($this->list[$delta])) {
        $this->list[$delta] = $this
          ->createItem($value);
      }
      else {
        $this->list[$delta]
          ->setValue($value);
      }
    }
  }
  else {
    $this->list = array();
  }
}