You are here

public function EntityReferenceRevisionsItem::setValue in Entity Reference Revisions 8

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

Parameters

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

Overrides EntityReferenceItem::setValue

File

src/Plugin/Field/FieldType/EntityReferenceRevisionsItem.php, line 155

Class

EntityReferenceRevisionsItem
Defines the 'entity_reference_revisions' entity field type.

Namespace

Drupal\entity_reference_revisions\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_revision_id', $values) && !isset($values['entity'])) {
      $this
        ->onChange('target_revision_id', FALSE);
    }
    elseif (is_array($values) && !array_key_exists('target_id', $values) && !array_key_exists('target_revision_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.
      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
      ->getParent()) {
      $this
        ->getParent()
        ->onChange($this
        ->getName());
    }
  }
}