Hello everyone,

I have been playing around with the new Constraint Plugin system in Drupal 8 and was trying to create my own Constraint & ConstraintValidator. It is supposed to count nodes and prevent new nodes from being saved if a certain number of nodes is reached. This is what I got:

MaxNodeCountConstraint.php

<?php

namespace Drupal\mymodule\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;


/**
 * Checks if a user name is unique on the site.
 *
 * @Plugin(
 *   id = "MaxNodeCount",
 *   label = @Translation("Max node count", context = "Validation"),
 *   type = {"entity"}
 * )
 */
class MaxNodeCountConstraint extends Constraint{

  public $message = 'The maximum limit of content is reached.';

}

MaxNodeCountConstraintValidator.php

<?php

namespace Drupal\mymodule\Plugin\Validation\Constraint;

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

class MaxNodeCountConstraintValidator extends ConstraintValidator {

  /**
  * {@inheritdoc}
  */
  public function validate($entity, Constraint $constraint) {
    if (isset($entity)) {
      // some logic
    }
  }
}

mymodule.module

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->addConstraint('MaxNodeCount');
}

Now I set a breakpoint inside the validate() function. However Drupal never runs that code. mymodule_entity_type_build is run when the module is enabled. The constraint is added successfully.
What am I doing wrong?

Thanks!

Comments

webiator GmbH’s picture

After a lot of digging I answered my own question: Drupal 8 beta11 does not fire EntityValidation. The latest dev version does it right, so in drupal 8 beta12 this issue will be fixed.