function EntityReferenceUuidItem::setValue

Overrides EntityReferenceItem::setValue

File

core/modules/jsonapi/tests/modules/jsonapi_test_field_type/src/Plugin/Field/FieldType/EntityReferenceUuidItem.php, line 97

Class

EntityReferenceUuidItem
Defines the 'entity_reference_uuid' entity field type.

Namespace

Drupal\jsonapi_test_field_type\Plugin\Field\FieldType

Code

public function setValue($values, $notify = TRUE) : void {
  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' or 'target_uuid' depending on values type.
    if (is_object($values)) {
      $this->set('entity', $values, $notify);
    }
    else {
      $this->set('target_uuid', $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_uuid', $values) && !isset($values['entity'])) {
      $this->onChange('target_uuid', FALSE);
    }
    elseif (is_array($values) && !array_key_exists('target_uuid', $values) && isset($values['entity'])) {
      $this->onChange('entity', FALSE);
    }
    elseif (is_array($values) && array_key_exists('target_uuid', $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_uuid will be different, due to the new
      // entity marker.
      $entity_uuid = $this->get('entity')
        ->get('uuid');
      // If the entity has been saved and we're trying to set both the
      // target_uuid and the entity values with a non-null target UUID, then
      // the value for target_uuid should match the UUID of the entity value.
      if (!$this->entity
        ->isNew() && $values['target_uuid'] !== NULL && $entity_uuid !== $values['target_uuid']) {
        throw new \InvalidArgumentException('The target UUID 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());
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.