2

How could I configure a unique constraint on several fields of a custom entity I have already created with drupalconsole.

The purpose is not allowing insert of two record of the same entity having for example same lastname and fisrtname.

2

As suggested by elstevenson, I used the validation API.

Here the steps.

  1. Create a repository in your module repo. /src/Plugin/Validation/Constraint
  2. Create a constraint (name = Unique)

    namespace Drupal\module_name\Plugin\Validation\Constraint;
    use Symfony\Component\Validator\Constraint;
    
    /**
    * @Constraint(
    *   id = "Unique",
    *   label = @Translation("Unique ", context = "Validation"),
    *   type = "entity:entity_name"`
    * )
    */
    
    
    class UniqueConstraint extends Constraint {
       public $message= 'Unique entity!';
       }
    
  3. Create a constraintValidator, and we populate the validate method with an entity query to make sure that there is no record having the same value of field1 and field 2:

     namespace Drupal\module_name\Plugin\Validation\Constraint;
     use Symfony\Component\Validator\Constraint;
     use Symfony\Component\Validator\ConstraintValidator;
    
    class UniqueConstraintValidator extends ConstraintValidator {
    
    /**
     * {@inheritdoc}
     */
    public function validate($entity, Constraint $constraint) {
     $field1 = $entity->field1->value;
     $field2 = $entity->field2->value;
     $entity_type_id = $entity->getEntityTypeId();
     $value_taken = (bool) \Drupal::entityQuery($entity_type_id)
      ->condition('field1',  $field1)
      ->condition('field2',  $field2)
      ->range(0, 1)
      ->count()
      ->execute();
    if ($value_taken)
    {
    $this->context->addViolation($constraint->message);
    
    }
    

    } }

  4. Then configure our constraint in our entity (annotations part):

/**

* Defines the entity_name entity.

*

    * @ingroup entity_name
    *
    * @ContentEntityType(
    *   id = "entity_name",
    *   label = @Translation("entity_name"),
    *   handlers = {
    *     ...
    *     "form" = {
    *     ..
    *     },
    *  ....
    *  
    *   constraints = {
    *     "Unique" = {}
    *   }
    * )
    */
  1. Then you should uninstall your module and then reinstall it . (if your entity is populated with data, you have to delete all the date).
  2. In your code (for example in your form) , you have to ensure the validation :

    $violations = $entity->validate();
    if ($violations->count() > 0) 
    {
     $violation = $violations[0];
    
     drupal_set_message($violation->getMessage(),'warning');
    }
    

Hope it will help.

0

I asked something similar a little while ago: How do I do a 'required if other field = x' using the entity validation api?

Basically, you want to use the Entity Validation API to create a Validation Plugin for your form.

  • thanks, but my need is a validating in database insert. It's basically adding a constraint unique in databse – Asy Sep 22 '16 at 12:58
  • 1
    Yes. What you'd want to do it what I described in my own answer to the question (drupal.stackexchange.com/a/215280/66405), ie create an Validation Plugin for your entity. If you go into the Comment module in core modules, there's a check against database content in that. There's some more notes on what I did in the answer I linked to. – elstevenson Sep 22 '16 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.