0

Here is a very simple code:

1-My constraint plugin (MyConstraint.php)

/**
 * @Constraint(
 *   id = "MyConstraint",
 *   label = @Translation("Never Validated", context = "Validation"),
 *   type = "string"
 * )
 */
class MyConstraint extends Constraint {
  public $message = "error %value";
}

2-My constraint validator (MyConstraintValidator.php) [=>addViolation in all cases]

class MyConstraintValidator extends ConstraintValidator {

  public function validate($items, Constraint $constraint) {
    dpm("I am displayed");
    $this->context->addViolation($constraint->message, [
              '%value' => 10
            ]);
    return;
}

3-My constraint added to my bundle

function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if($bundle=='my_bundle'){
      $fields['my_paragraph_field']->addConstraint('MyConstraint', []);
    }
}

Result:

1-The dpm message 'I am displayed' is displayed

2-The entity is saved without any validation error

Notes:

-I have other constraints which are working well, If I test one of them (on my_bundle), the violation of this working constraint will be displayed but not the one with the code detailled here.

-The problematic constraint is added to a paragraph field... I suspect the problem is coming from there

-Nothing in the error logs.

I am looking for a hint to where to look.

3 Answers 3

0

On your addConstraint() your second parameter is an empty array - if you do not want to add any options leave that empty or use NULL

3
  • Thank you for your help, but this doesn't change anything. Moreover I have added this empty array in all other constraints of my project and they are working well.. (Anyway I have tested without the empty array)
    – Baud
    Commented Sep 15, 2020 at 14:36
  • ok, pitty... did you try to follow the method with Xdebug or something? What is happening in $this->context->addViolation? Might it have something to do with paragraphs? When you add this constraint to a node field instead of a paragraph field is that working? Commented Sep 15, 2020 at 14:40
  • I have added this constraint to another field and it is working...
    – Baud
    Commented Sep 15, 2020 at 15:03
0

Ok, I found the solution...

It was a widget problem!! As I used a custom widget for this paragraph field, I didn't realize that the widget was also handling part of the violation process inside the function flagErrors which was badly overroded.

Sorry for this

-1

You need to add

namespace Drupal\my_module\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;


/**
 * Validates the MyConstraint .
 */
class MyConstraintValidator extends ConstraintValidator {


  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {

    if (!$item = $items->first()) {
      return;
    }

    $field_name = $items->getFieldDefinition()->getName();

    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();

    if ($entity->hasField('my_paragraph_field')) {

      $value = $entity->my_paragraph_field->value;


      // Check if the value matches or not.
      if ($value != 10) {

        $this->context->addViolation($constraint->message, [
          '%value' => 10
        ]);
      }

    }

  }

}

For reference : Adding Constraint to entity referenced Paragraph field

6
  • thank you for your help. Unfortunately it is not correct: $entity_type->id() is a Node, not a paragraph. But my_paragraph_field is referencing a paragraph. As you can see in my OP, the constraint is called (dpm("I am displayed")) thus I don't think the problem is coming from mymodule_entity_bundle_field_info_alter
    – Baud
    Commented Sep 10, 2020 at 7:27
  • @Baud I over looked your question, I have added the correct code now. You need to get the paragraph entity first and its fields to get the field value and later add validations to it. Commented Sep 10, 2020 at 9:07
  • Sorry, but this doesn't work: $entity->hasField('my_paragraph_field') is useless because we have added the constraint to this field. Note that the code in the OP Is adding the violation in all cases (no test on a value) to make sure the problem is not in the code which is checking the value. The validate function create only the violation and display "I am displayed" to confirm that the function has been called. The issues are "Why the constraint message is not displayed" and "Why there is no validation failure"
    – Baud
    Commented Sep 10, 2020 at 10:58
  • Constraint will be called everywhere as you have added it in field info alter. The problem here is constraint is not being applied because it can not get the value. Have you tried to execute my code ? In what places the paragraph is being used? If it is being used in a node just copy paste my code and execute it. Constraint will be applied. Commented Sep 10, 2020 at 11:54
  • Were you able to get the field value printed in the constraint validate method ? First try to get the field value and you can apply validation once you have the variable for the field. Commented Sep 10, 2020 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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