3 namespace Drupal\Core\Entity\Plugin\Validation\Constraint;
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
7 use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface;
8 use Drupal\Core\Entity\EntityTypeManagerInterface;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\Validator\Constraint;
11 use Symfony\Component\Validator\ConstraintValidator;
14 * Checks if referenced entities are valid.
16 class ValidReferenceConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
19 * The selection plugin manager.
21 * @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface
23 protected $selectionManager;
26 * The entity type manager.
28 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
30 protected $entityTypeManager;
33 * Constructs a ValidReferenceConstraintValidator object.
35 * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selection_manager
36 * The selection plugin manager.
37 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
38 * The entity type manager.
40 public function __construct(SelectionPluginManagerInterface $selection_manager, EntityTypeManagerInterface $entity_type_manager) {
41 $this->selectionManager = $selection_manager;
42 $this->entityTypeManager = $entity_type_manager;
48 public static function create(ContainerInterface $container) {
50 $container->get('plugin.manager.entity_reference_selection'),
51 $container->get('entity_type.manager')
58 public function validate($value, Constraint $constraint) {
59 /** @var \Drupal\Core\Field\FieldItemListInterface $value */
60 /** @var ValidReferenceConstraint $constraint */
65 // Collect new entities and IDs of existing entities across the field items.
68 foreach ($value as $delta => $item) {
69 $target_id = $item->target_id;
70 // We don't use a regular NotNull constraint for the target_id property as
71 // NULL is allowed if the entity property contains an unsaved entity.
72 // @see \Drupal\Core\TypedData\DataReferenceTargetDefinition::getConstraints()
73 if (!$item->isEmpty() && $target_id === NULL) {
74 if (!$item->entity->isNew()) {
75 $this->context->buildViolation($constraint->nullMessage)
76 ->atPath((string) $delta)
80 $new_entities[$delta] = $item->entity;
83 // '0' or NULL are considered valid empty references.
84 if (!empty($target_id)) {
85 $target_ids[$delta] = $target_id;
89 // Early opt-out if nothing to validate.
90 if (!$new_entities && !$target_ids) {
94 $entity = !empty($value->getParent()) ? $value->getEntity() : NULL;
96 /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler * */
97 $handler = $this->selectionManager->getSelectionHandler($value->getFieldDefinition(), $entity);
98 $target_type_id = $value->getFieldDefinition()->getSetting('target_type');
100 // Add violations on deltas with a new entity that is not valid.
102 if ($handler instanceof SelectionWithAutocreateInterface) {
103 $valid_new_entities = $handler->validateReferenceableNewEntities($new_entities);
104 $invalid_new_entities = array_diff_key($new_entities, $valid_new_entities);
107 // If the selection handler does not support referencing newly created
108 // entities, all of them should be invalidated.
109 $invalid_new_entities = $new_entities;
112 foreach ($invalid_new_entities as $delta => $entity) {
113 $this->context->buildViolation($constraint->invalidAutocreateMessage)
114 ->setParameter('%type', $target_type_id)
115 ->setParameter('%label', $entity->label())
116 ->atPath((string) $delta . '.entity')
117 ->setInvalidValue($entity)
122 // Add violations on deltas with a target_id that is not valid.
124 // Get a list of pre-existing references.
125 $previously_referenced_ids = [];
126 if ($value->getParent() && ($entity = $value->getEntity()) && !$entity->isNew()) {
127 $existing_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
128 foreach ($existing_entity->{$value->getFieldDefinition()->getName()}->getValue() as $item) {
129 $previously_referenced_ids[$item['target_id']] = $item['target_id'];
133 $valid_target_ids = $handler->validateReferenceableEntities($target_ids);
134 if ($invalid_target_ids = array_diff($target_ids, $valid_target_ids)) {
135 // For accuracy of the error message, differentiate non-referenceable
136 // and non-existent entities.
137 $existing_entities = $this->entityTypeManager->getStorage($target_type_id)->loadMultiple($invalid_target_ids);
138 foreach ($invalid_target_ids as $delta => $target_id) {
139 // Check if any of the invalid existing references are simply not
140 // accessible by the user, in which case they need to be excluded from
142 if (isset($previously_referenced_ids[$target_id]) && isset($existing_entities[$target_id]) && !$existing_entities[$target_id]->access('view')) {
146 $message = isset($existing_entities[$target_id]) ? $constraint->message : $constraint->nonExistingMessage;
147 $this->context->buildViolation($message)
148 ->setParameter('%type', $target_type_id)
149 ->setParameter('%id', $target_id)
150 ->atPath((string) $delta . '.target_id')
151 ->setInvalidValue($target_id)