You are here

public function EntityReferenceItem::setValue in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue()

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

Parameters

array|null $values: An array of property values.

bool $notify: (optional) Whether to notify the parent object of the change. Defaults to TRUE. If a property is updated from a parent object, set it to FALSE to avoid being notified again.

Overrides FieldItemBase::setValue

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php, line 175

Class

EntityReferenceItem
Defines the 'entity_reference' entity field type.

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

Code

public function setValue($values, $notify = TRUE) {
  if (isset($values) && !is_array($values)) {

    // If either a scalar or an object was passed as the value for the item,
    // assign it to the 'entity' property since that works for both cases.
    $this
      ->set('entity', $values, $notify);
  }
  else {
    parent::setValue($values, FALSE);

    // Support setting the field item with only one property, but make sure
    // values stay in sync if only property is passed.
    // NULL is a valid value, so we use array_key_exists().
    if (is_array($values) && array_key_exists('target_id', $values) && !isset($values['entity'])) {
      $this
        ->onChange('target_id', FALSE);
    }
    elseif (is_array($values) && !array_key_exists('target_id', $values) && isset($values['entity'])) {
      $this
        ->onChange('entity', FALSE);
    }
    elseif (is_array($values) && array_key_exists('target_id', $values) && isset($values['entity'])) {

      // If both properties are passed, verify the passed values match. The
      // only exception we allow is when we have a new entity: in this case
      // its actual id and target_id will be different, due to the new entity
      // marker.
      $entity_id = $this
        ->get('entity')
        ->getTargetIdentifier();

      // If the entity has been saved and we're trying to set both the
      // target_id and the entity values with a non-null target ID, then the
      // value for target_id should match the ID of the entity value. The
      // entity ID as returned by $entity->id() might be a string, but the
      // provided target_id might be an integer - therefore we have to do a
      // non-strict comparison.
      if (!$this->entity
        ->isNew() && $values['target_id'] !== NULL && $entity_id != $values['target_id']) {
        throw new \InvalidArgumentException('The target id and entity passed to the entity reference item do not match.');
      }
    }

    // Notify the parent if necessary.
    if ($notify && $this->parent) {
      $this->parent
        ->onChange($this
        ->getName());
    }
  }
}