
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:
- use Drupal\Core\Entity\EntityTypeInterface;
- /**
- * Implements hook_entity_bundle_field_info_alter.
- */
- function foundation_anchor_menu_block_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
- if ($entity_type->id() == 'block_content' && $bundle == 'famb_anchor' && !empty($fields['field_block_famb_anchor_id'])) {
- $fields['field_block_famb_anchor_id']->setPropertyConstraints('value', [
- 'Regex' => [
- 'pattern' => '/^[A-Za-z]+[\w\-\:\.]*$/',
- '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 (".").'),
- ],
- ]);
- }
- }
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...
- Login to post comments
Julian Pustkuchen, M. Sc. Wirtschaftsinformatik ist passionierter Software- & Webentwickler mit den Schwerpunkten Softwaredesign, Objektorientierung sowie Usability- & Ablaufoptimierung bei webks. Ein weiterer Schwerpunkt ist die Entwicklung im CMS Drupal.
Entwickelt Julian gerade keine Software, fährt er Ski, Mountainbike, spielt Badminton, segelt oder verbringt Zeit mit Freunden.
Dieser Blog dient als sein "öffentlicher Notizblo(ck/g)".
Webbasierte Lösungen? Machen wir!
webks: websolutions kept simple
http://www.webks.de
Dir hat dieser Beitrag viel Zeit und Nerven gespart?
Dann freue ich mich über jede kleine Anerkennung:
Oder du suchst weitere professionelle Unterstützung?
Dann bietet dir unser webks.de Softwareentwickler-Team professionelle Dienstleistungen im Web-Development und der Drupal CMS Entwicklung!