public function DynamicEntityReferenceItem::setValue in Dynamic Entity Reference 8
Same name and namespace in other branches
- 8.2 src/Plugin/Field/FieldType/DynamicEntityReferenceItem.php \Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceItem::setValue()
Overrides \Drupal\Core\TypedData\TypedData::setValue().
Parameters
array|null $values: An array of property values.
Overrides EntityReferenceItem::setValue
File
- src/
Plugin/ Field/ FieldType/ DynamicEntityReferenceItem.php, line 421
Class
- DynamicEntityReferenceItem
- Defines the 'dynamic_entity_reference' entity field type.
Namespace
Drupal\dynamic_entity_reference\Plugin\Field\FieldTypeCode
public function setValue($values, $notify = TRUE) {
// 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.
if (isset($values) && !is_array($values)) {
$this
->set('entity', $values, $notify);
}
else {
if (empty($values['target_type']) && !empty($values['target_id']) && !(isset($values['entity']) && $values['entity'] instanceof EntityInterface)) {
throw new \InvalidArgumentException('No entity type was provided, value is not a valid entity.');
}
// We have to bypass the EntityReferenceItem::setValue() here because we
// also want to invoke onChange for target_type.
FieldItemBase::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) && array_key_exists('target_type', $values) && !isset($values['entity'])) {
$this
->onChange('target_type', FALSE);
$this
->onChange('target_id', FALSE);
}
elseif (is_array($values) && !array_key_exists('target_id', $values) && !array_key_exists('target_type', $values) && isset($values['entity'])) {
$this
->onChange('entity', FALSE);
}
elseif (is_array($values) && array_key_exists('target_id', $values) && array_key_exists('target_type', $values) && isset($values['entity'])) {
/** @var \Drupal\dynamic_entity_reference\Plugin\DataType\DynamicEntityReference $entity_property */
$entity_property = $this
->get('entity');
$entity_id = $entity_property
->getTargetIdentifier();
/** @var \Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface $target_definition */
$target_definition = $entity_property
->getTargetDefinition();
$entity_type = $target_definition
->getEntityTypeId();
if (!$this->entity
->isNew() && $values['target_id'] !== NULL && ($entity_id !== $values['target_id'] || $entity_type !== $values['target_type'])) {
throw new \InvalidArgumentException('The target id, target type and entity passed to the dynamic entity reference item do not match.');
}
}
// Notify the parent if necessary.
if ($notify && $this->parent) {
$this->parent
->onChange($this
->getName());
}
}
}