I implemented hook_entity_bundle_field_info_alter() to add validation to fields of a node type. I got $bundle as an argument in the hook and I need to pass it in $options argument like below:

$fields['field_tags']->addConstraint('NodeValidate', $bundle);

How can I access this argument in NodeValidateConstraintValidator? Am I passing the argument correctly?

$options provided in addConstraint can be accessed in the constructor using parent::__construct($options) in __construct() function build the options.

hook_entity_base_field_info_alter() doesn't contain a $bundle argument, as it is defined as function hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type). How can I validate the base field for a particular node type?

2 Answers 2

  1. Options needs to be an array I think. You can access it on the constraint object in your validator, see ListStringItem::propertyDefinitions() and LengthValidator, which then uses it as $constraint->max.

  2. Base fields are exactly that. Base fields. There is no bundle, they are the same for all bundles of an entity type (they can be overriden per-bundle, but then they become accessible in the bundle hook).

  3. You shouldn't ask two different questions together :)

  • Sorry for asking two questions on a single post. I'm a bit lazy :( . Can you please explain the 2nd point that states overriding per-bundle. If i need to validate title field of a particular node type which hook should I use? Jun 26, 2015 at 7:18
  • I looked at propertyDefinitions() and LengthValidator and tried to do the same but it just throwed me an error. I think there is something to do with constructor in Length.php . But I can't get it Jun 26, 2015 at 10:39

To pass arguments in addConstraint() something like:

$fields['field_tags]->addConstraint('NodeValidate', array('bundle' => 'article));

You should create a constructor in NodeValidateConstraint.php and calling the parent constructor like below:

You should need to declare a property name same as the name of the key in the options you passed. In this case it is bundle.

class NodeValidateConstraint extends Constraint {
  public $bundle;
  public function __construct($options = null)

Now you could access the $options in NodeValidateConstraintValidator.php as

$bundle_name = $constraint->bundle;

Thanks berdir for guiding me in this and continuously responding to my queries in drupal 8:)

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.