Drupal 8: Add field validation constraint programmatically

In foundation_anchor_menu_block module I needed to add a validation to a field in a block to ensure the entered value matches the regex allowed for an "id" HTML element attribute.

This is quite simple using Drupal 8 and Symfony Constraints / Validators:

  1. use Drupal\Core\Entity\EntityTypeInterface;
  2.  
  3. /**
  4.  * Implements hook_entity_bundle_field_info_alter.
  5.  */
  6. function foundation_anchor_menu_block_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  7.   if ($entity_type->id() == 'block_content' && $bundle == 'famb_anchor' && !empty($fields['field_block_famb_anchor_id'])) {
  8.     $fields['field_block_famb_anchor_id']->setPropertyConstraints('value', [
  9.       'Regex' => [
  10.         'pattern' => '/^[A-Za-z]+[\w\-\:\.]*$/',
  11.         'message' => t('The ID must begin with a letter ([A-Za-z]) and may be followed by any number of letters ([A-Za-z]), digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").'),
  12.       ],
  13.     ]);
  14.   }
  15. }

GREAT article about that can be found here:
https://jigarius.com/blog/drupal-entity-validation-api

Module alternative: https://www.drupal.org/project/rfv

Also see:
https://www.drupal.org/docs/8/api/entity-api/entity-validation-api/provi...
https://blog.codeenigma.com/introduction-to-drupal-8-entity-validation-f...
https://drupal.stackexchange.com/questions/202481/how-to-use-regexconstr...
https://drupal.stackexchange.com/questions/226275/how-can-i-add-a-constr...

Kommentare

Kommentar hinzufügen

Der Inhalt dieses Feldes wird nicht öffentlich zugänglich angezeigt.

Weitere Informationen über Formatierungsoptionen