<?php
* @file
* Contains \Drupal\our_custom_module_name\Plugin\Validation\Constraint\ExistsEntityWithNameConstraintValidator.
*/
namespace Drupal\our_custom_module_name\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
* Validates the ExistsEntityWithNameConstraint.
*/
class ExistsEntityWithNameConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
* Validator 2.5 and upwards compatible execution context.
*
* @var \Symfony\Component\Validator\Context\ExecutionContextInterface
*/
protected $context;
* @var \Drupal\Core\Entity\EntityTypeManager
*/
protected $entityTypeManager;
* Constructs a new ExistsEntityWithNameConstraintValidator.
*
* @param \Drupal\Core\Entity\EntityTypeManager
* The user storage handler.
*/
public function __construct(EntityTypeManager $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('entity_type.manager'));
}
* {@inheritdoc}
*
* Here we validate entities and check if the same entity
* (with the same name) already exists.
*/
public function validate($entity, Constraint $constraint) {
$name = $entity->name->value;
if (isset($name)) {
$entity_storage = $this->entityTypeManager->getStorage($entity->bundle());
$ex_entity = $entity_storage->loadByProperties(array('name'=> $name));
if (!empty($ex_entity) && is_array($ex_entity)) {
$ex_entity_id = array_shift($ex_entity)->id();
if ($entity->id() != $ex_entity_id) {
$this->context->buildViolation($constraint->messageExists, array(
'%entity' => $name
))
->atPath('name')
->addViolation();
}
}
}
}
}