Skip to content

Instantly share code, notes, and snippets.

@welly
Created April 5, 2016 03:50
Show Gist options
  • Save welly/3a34e5a743094b85aa2fbcfed3e62d9c to your computer and use it in GitHub Desktop.
Save welly/3a34e5a743094b85aa2fbcfed3e62d9c to your computer and use it in GitHub Desktop.
public function validate($item, Constraint $constraint) {
if ($item->isEmpty()) {
return NULL;
}
$entity = $item->getEntity();
$entity_id = $entity->id();
$entity_type = $entity->getEntityType();
$field_name = $item->getFieldDefinition()->getName();
$properties = $item->getProperties();
// Query to see if existing entity with machine name exists.
$query = \Drupal::entityQuery($entity_type->id());
foreach ($properties as $property) {
$query->condition($field_name . '.value', $property->getValue());
if (!empty($entity_id)) {
$query->condition('entity.id', $entity_id, '<>');
}
$result = $query->execute();
if (count($result) > 0) {
$this->context->addViolation($constraint->message, array('%entity_type' => $entity_type->id(), '%value' => $property->getValue()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment