SlideShare a Scribd company logo
LISBON 2018
DRUPAL DEVELOPER DAYS
Validate your entities with symfony
validator and Entity Validation API
Raffaele Chiocca
Diamond Sponsor
Platinum Sponsors
Gold Sponsors
• Software Engineer @Ibuildings
• Drupal developer since 2011
• Drupal 8 core contributor
• Contrib modules maintainer:
- Paragraphs React (D8)
- jQuery Touch Swipe (D7,D8)
- Paragraphs Wizard (D8)
• D8 flag module contributor
• Actually contributing at webform encrypt
• https://www.drupal.org/u/rafuel92
About me
i’ll assume you know something about :
• Plugins in D8
• Entities in D8
Drupal 8 Background
Here’s What’s In The Session
• Validation in modern web applications
• D8 Entity Validation API Architecture
• How to create a constraint validation plugin in D8
• Practical examples with clean validations in a drupal 8 web
application using custom defined constraints.
• How to perform automated tests on your constraints.
Input validation, aka data validation, is the proper testing of
any input supplied by a user or application.
Input validation prevents improperly formed data from
entering an information system.
Data Validation
Ensures supplied data is :
Strongly typed
Has Correct Syntax
Within length boundaries
Contains only permitted characters
Data Validation
Server-side
- In the logic that receives
submissions
- Drupal handles some automatically
- Required for secure inputs
- Can be a black box for users if
incorrectly handled
Where Validation Happens
Client-side
- Usually javascript based
- Included in the spec of some
HTML5 fields
- Provides rapid feedback
- Easy to elude
Validation in D7
form_alter to the target form
$form['#validate'][] = 'my_test_validate';
Problems with D7 approach
Data also needs to be validated when is received from mobile
apps, javascript apps or other external systems.
Forms are not the only way you create entities
(REST API, Rules node generation, secondary forms, data
migrations)
What is Entity Validation API?
Validates content entities on multiple levels
Returns a list of violations when validation fails
Happens automatically in entity form validation
It’s not part of the form API
Guarantees the data integrity of your entities
Why entity validation API
REST, GraphQL Mutations
Custom entity generation code
Migrations
Rules module
Whenever you manipulate an entity outside of the entity form
Symfony Validator Overview
Symfony provides a Validator component that makes this task
easy and transparent. This component is based on the JSR303
Bean Validation specification.
Entity Validation API Overview (1/2)
In Drupal 8 Entity validation is moved to a separate Entity
validation API and decoupled from form validation.
Decoupling entity validation from forms allows validation entities to
be independent of form submissions, such as when changed via
the RESTful web service.
Entity Validation API Overview (2/2)
Validation is controlled by a set of constraints, such as the
maximum length of some text or restriction to a set of allowed
values.
Symfony comes with many useful constraints, which Drupal
extends with more Drupal-specific constraints.
How to invoke entity validation?
$violations = $entity->validate()
Or on a field :
$violations = $entity->get(‘foo’)->validate()
Returns an EntityConstraintViolationList
Checking for violations
$violations->count();
Implements IteratorAggregate
Checking for violations
$violations->getEntityViolations();
$violations->getByField(‘field_foo’);
$violations->filterByFields([‘foo1’,’foo2’])
Reading violations
$violations->getMessage();
Other methods on violations
$violation->getInvalidValue();
All violations implements a common interface
SymfonyComponentValidatorConstraintViolationInterface
Where do violations come from?
ContentEntityBase.php
Four main levels of validation
The entity as whole
A field on an entity
Field entries in a field
The single instance of a field entry
Examples of the four Entity Validation API levels
$node
$node->myfield
$node->myfield[0]
$node->myfield[0][‘value’]
Four levels interfaces
ContentEntityInterface
FieldItemListInterface
FieldItemInterface
Property
Four levels validation responsibilities
ContentEntityInterface
FieldItemListInterface
FieldItemInterface
Property
How to create a custom constraint validation plugin in D8
Two classes :
1. A constraint plugin
2. The actual validator class (contains validation logic, can also be
re-used)
The constraint plugin (1/2)
A unique ID
A human readable label
A type (string) or a list of types (Array)
in a custom module  Src/Plugin/Validation/Constraint
The constraint plugin (2/2)
CompositeConstraintBase
Steps to create the Actual ValidatorCreate a class called “{ConstraintClassName}Validator” under
Src/Plugin/Validation/Constraint
(i.e “BundleConstraint” -> ”BundleConstraintValidator”)
Implement a validate method with two parameters
($items, SymfonyComponentValidatorConstraint $constraint)
$items is the element that you are actually validating
(so if you are a validating a field you’ll receive a FieldItemList)
$constraint is an instance of {ConstraintClassName} object, you can use
$constraint to get the messages to show to the end-user when add/building a
violation.
Create the actual validator
Generate Violations
The Validation Context ($this-
>context)The Context of a validation Run.
The context actually collects all violations generated during the validation.
By default, validators execute all validations in a new context,
in a validation run we add violations to a context
@see ExecutionContextInterface
Examples :
$node>validate() (the context is the $node)
$node->get(‘field_bad’)->validate() (in this case the context is a FieldItemList)
Property path
Using the property path you can specify where the violation
occurred
(i.e. specify that only a field of an entity is not valid)
The property path is also used to show form errors to the end-
user.
Property path Example
* <pre>
* (Person)---($address: Address)---($street: string)
* </pre>
*
* When the <tt>Person</tt> instance is passed to the validator, the
* property path is initially empty. When the <tt>$address</tt>
property
* of that person is validated, the property path is "address". When
* the <tt>$street</tt> property of the related <tt>Address</tt>
instance
* is validated, the property path is "address.street".
Drupal Property path examples
When validating an entity
Field_bad.0.entity
Field_good.2
When validating a field
3.value
When validating a field entry
target_id
quantity
Setting property path of a Violation
$this->context->buildViolation($constraint->message)
->atPath(“field_bad”)
->addViolation()
Stores the property path at which the violation should be generated.
The passed path will be appended to the current property path of the
execution context.
“ H O W T O A P P L Y
V A L I D A T O R S ? ”
Apply Validators in a new custom
entity
Apply Validators for existing entity
types
Apply Validators to Base Fields
Apply Validators to Existing fields (1/2)
hook_entity_base_field_info_alter(&$fields,
DrupalCoreEntityEntityTypeInterface $entity_type)
hook_entity_bundle_field_info_alter(&$fields,
DrupalCoreEntityEntityTypeInterface $entity_type, $bundle)
->addConstraint
Apply Validators to Existing fields (2/2)
For a @FieldType
Field property level
“ P R A C T I C A L E X A M P L E S
S E C T I O N ”
Practical examples 1
Use of tokens in constraint messages
How we can practically use symfony validator to validate
paragraphs inside a ContentEntity
Practical examples 2
Create a PHPUnit test extending KernelTestBase
Create a TestValidation Method
Create your entity programmatically
$violations = $my_entity->validate();
$this->assertEqual($violations->count(), 0, 'Validation passed for
correct value.');
Testing a constraint (1/2)
Testing a constraint (2/2)
–Raffaele Chiocca
“ Q U E S T I O N S ? ”
Ad

Recommended

Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Understanding react hooks
Understanding react hooks
Samundra khatri
 
React Js Simplified
React Js Simplified
Sunil Yadav
 
React JS and why it's awesome
React JS and why it's awesome
Andrew Hull
 
spring-boot-fr.pdf
spring-boot-fr.pdf
seydou4devops
 
React-JS.pptx
React-JS.pptx
AnmolPandita7
 
Spring Boot
Spring Boot
Jaran Flaath
 
The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
what is functional component
what is functional component
manojbkalla
 
Js scope
Js scope
santhosh kumar.s sampath.v
 
Web programming
Web programming
Leo Mark Villar
 
Selenium Maven With Eclipse | Edureka
Selenium Maven With Eclipse | Edureka
Edureka!
 
Blazor - An Introduction
Blazor - An Introduction
JamieTaylor112
 
JavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Jenkins CI presentation
Jenkins CI presentation
Jonathan Holloway
 
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
Edureka!
 
JavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
An introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
Scaling up task processing with Celery
Scaling up task processing with Celery
Nicolas Grasset
 
Intro to vue.js
Intro to vue.js
TechMagic
 
Selenium ppt
Selenium ppt
Naga Dinesh
 
Webinar: Selenium WebDriver - Automation Uncomplicated
Webinar: Selenium WebDriver - Automation Uncomplicated
Edureka!
 
Container Runtime Security with Falco
Container Runtime Security with Falco
Michael Ducy
 
Laravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web Artisans
Windzoon Technologies
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec Jenkins
Eric Hogue
 
Introduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Loops in java script
Loops in java script
Ravi Bhadauria
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
Cadastral Maps
Cadastral Maps
Google
 

More Related Content

What's hot (20)

what is functional component
what is functional component
manojbkalla
 
Js scope
Js scope
santhosh kumar.s sampath.v
 
Web programming
Web programming
Leo Mark Villar
 
Selenium Maven With Eclipse | Edureka
Selenium Maven With Eclipse | Edureka
Edureka!
 
Blazor - An Introduction
Blazor - An Introduction
JamieTaylor112
 
JavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Jenkins CI presentation
Jenkins CI presentation
Jonathan Holloway
 
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
Edureka!
 
JavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
An introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
Scaling up task processing with Celery
Scaling up task processing with Celery
Nicolas Grasset
 
Intro to vue.js
Intro to vue.js
TechMagic
 
Selenium ppt
Selenium ppt
Naga Dinesh
 
Webinar: Selenium WebDriver - Automation Uncomplicated
Webinar: Selenium WebDriver - Automation Uncomplicated
Edureka!
 
Container Runtime Security with Falco
Container Runtime Security with Falco
Michael Ducy
 
Laravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web Artisans
Windzoon Technologies
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec Jenkins
Eric Hogue
 
Introduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Loops in java script
Loops in java script
Ravi Bhadauria
 
what is functional component
what is functional component
manojbkalla
 
Selenium Maven With Eclipse | Edureka
Selenium Maven With Eclipse | Edureka
Edureka!
 
Blazor - An Introduction
Blazor - An Introduction
JamieTaylor112
 
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
React Components Lifecycle | React Tutorial for Beginners | ReactJS Training ...
Edureka!
 
JavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
An introduction to React.js
An introduction to React.js
Emanuele DelBono
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
Scaling up task processing with Celery
Scaling up task processing with Celery
Nicolas Grasset
 
Intro to vue.js
Intro to vue.js
TechMagic
 
Webinar: Selenium WebDriver - Automation Uncomplicated
Webinar: Selenium WebDriver - Automation Uncomplicated
Edureka!
 
Container Runtime Security with Falco
Container Runtime Security with Falco
Michael Ducy
 
Laravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web Artisans
Windzoon Technologies
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec Jenkins
Eric Hogue
 
Introduction to Javascript
Introduction to Javascript
Amit Tyagi
 

Recently uploaded (20)

02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
Cadastral Maps
Cadastral Maps
Google
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
ijab2
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
ElysiumPro Company Profile 2025-2026.pdf
ElysiumPro Company Profile 2025-2026.pdf
info751436
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
Cadastral Maps
Cadastral Maps
Google
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
ijab2
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Great power lithium iron phosphate cells
Great power lithium iron phosphate cells
salmankhan835951
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
ElysiumPro Company Profile 2025-2026.pdf
ElysiumPro Company Profile 2025-2026.pdf
info751436
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Ad

Validate your entities with symfony validator and entity validation api

  • 1. LISBON 2018 DRUPAL DEVELOPER DAYS Validate your entities with symfony validator and Entity Validation API Raffaele Chiocca
  • 5. • Software Engineer @Ibuildings • Drupal developer since 2011 • Drupal 8 core contributor • Contrib modules maintainer: - Paragraphs React (D8) - jQuery Touch Swipe (D7,D8) - Paragraphs Wizard (D8) • D8 flag module contributor • Actually contributing at webform encrypt • https://www.drupal.org/u/rafuel92 About me
  • 6. i’ll assume you know something about : • Plugins in D8 • Entities in D8 Drupal 8 Background
  • 7. Here’s What’s In The Session • Validation in modern web applications • D8 Entity Validation API Architecture • How to create a constraint validation plugin in D8 • Practical examples with clean validations in a drupal 8 web application using custom defined constraints. • How to perform automated tests on your constraints.
  • 8. Input validation, aka data validation, is the proper testing of any input supplied by a user or application. Input validation prevents improperly formed data from entering an information system. Data Validation
  • 9. Ensures supplied data is : Strongly typed Has Correct Syntax Within length boundaries Contains only permitted characters Data Validation
  • 10. Server-side - In the logic that receives submissions - Drupal handles some automatically - Required for secure inputs - Can be a black box for users if incorrectly handled Where Validation Happens Client-side - Usually javascript based - Included in the spec of some HTML5 fields - Provides rapid feedback - Easy to elude
  • 11. Validation in D7 form_alter to the target form $form['#validate'][] = 'my_test_validate';
  • 12. Problems with D7 approach Data also needs to be validated when is received from mobile apps, javascript apps or other external systems. Forms are not the only way you create entities (REST API, Rules node generation, secondary forms, data migrations)
  • 13. What is Entity Validation API? Validates content entities on multiple levels Returns a list of violations when validation fails Happens automatically in entity form validation It’s not part of the form API Guarantees the data integrity of your entities
  • 14. Why entity validation API REST, GraphQL Mutations Custom entity generation code Migrations Rules module Whenever you manipulate an entity outside of the entity form
  • 15. Symfony Validator Overview Symfony provides a Validator component that makes this task easy and transparent. This component is based on the JSR303 Bean Validation specification.
  • 16. Entity Validation API Overview (1/2) In Drupal 8 Entity validation is moved to a separate Entity validation API and decoupled from form validation. Decoupling entity validation from forms allows validation entities to be independent of form submissions, such as when changed via the RESTful web service.
  • 17. Entity Validation API Overview (2/2) Validation is controlled by a set of constraints, such as the maximum length of some text or restriction to a set of allowed values. Symfony comes with many useful constraints, which Drupal extends with more Drupal-specific constraints.
  • 18. How to invoke entity validation? $violations = $entity->validate() Or on a field : $violations = $entity->get(‘foo’)->validate() Returns an EntityConstraintViolationList
  • 22. Other methods on violations $violation->getInvalidValue(); All violations implements a common interface SymfonyComponentValidatorConstraintViolationInterface
  • 23. Where do violations come from? ContentEntityBase.php
  • 24. Four main levels of validation The entity as whole A field on an entity Field entries in a field The single instance of a field entry
  • 25. Examples of the four Entity Validation API levels $node $node->myfield $node->myfield[0] $node->myfield[0][‘value’]
  • 27. Four levels validation responsibilities ContentEntityInterface FieldItemListInterface FieldItemInterface Property
  • 28. How to create a custom constraint validation plugin in D8 Two classes : 1. A constraint plugin 2. The actual validator class (contains validation logic, can also be re-used)
  • 29. The constraint plugin (1/2) A unique ID A human readable label A type (string) or a list of types (Array) in a custom module  Src/Plugin/Validation/Constraint
  • 32. Steps to create the Actual ValidatorCreate a class called “{ConstraintClassName}Validator” under Src/Plugin/Validation/Constraint (i.e “BundleConstraint” -> ”BundleConstraintValidator”) Implement a validate method with two parameters ($items, SymfonyComponentValidatorConstraint $constraint) $items is the element that you are actually validating (so if you are a validating a field you’ll receive a FieldItemList) $constraint is an instance of {ConstraintClassName} object, you can use $constraint to get the messages to show to the end-user when add/building a violation.
  • 33. Create the actual validator
  • 35. The Validation Context ($this- >context)The Context of a validation Run. The context actually collects all violations generated during the validation. By default, validators execute all validations in a new context, in a validation run we add violations to a context @see ExecutionContextInterface Examples : $node>validate() (the context is the $node) $node->get(‘field_bad’)->validate() (in this case the context is a FieldItemList)
  • 36. Property path Using the property path you can specify where the violation occurred (i.e. specify that only a field of an entity is not valid) The property path is also used to show form errors to the end- user.
  • 37. Property path Example * <pre> * (Person)---($address: Address)---($street: string) * </pre> * * When the <tt>Person</tt> instance is passed to the validator, the * property path is initially empty. When the <tt>$address</tt> property * of that person is validated, the property path is "address". When * the <tt>$street</tt> property of the related <tt>Address</tt> instance * is validated, the property path is "address.street".
  • 38. Drupal Property path examples When validating an entity Field_bad.0.entity Field_good.2 When validating a field 3.value When validating a field entry target_id quantity
  • 39. Setting property path of a Violation $this->context->buildViolation($constraint->message) ->atPath(“field_bad”) ->addViolation() Stores the property path at which the violation should be generated. The passed path will be appended to the current property path of the execution context.
  • 40. “ H O W T O A P P L Y V A L I D A T O R S ? ”
  • 41. Apply Validators in a new custom entity
  • 42. Apply Validators for existing entity types
  • 43. Apply Validators to Base Fields
  • 44. Apply Validators to Existing fields (1/2) hook_entity_base_field_info_alter(&$fields, DrupalCoreEntityEntityTypeInterface $entity_type) hook_entity_bundle_field_info_alter(&$fields, DrupalCoreEntityEntityTypeInterface $entity_type, $bundle) ->addConstraint
  • 45. Apply Validators to Existing fields (2/2)
  • 48. “ P R A C T I C A L E X A M P L E S S E C T I O N ”
  • 49. Practical examples 1 Use of tokens in constraint messages
  • 50. How we can practically use symfony validator to validate paragraphs inside a ContentEntity Practical examples 2
  • 51. Create a PHPUnit test extending KernelTestBase Create a TestValidation Method Create your entity programmatically $violations = $my_entity->validate(); $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.'); Testing a constraint (1/2)
  • 53. –Raffaele Chiocca “ Q U E S T I O N S ? ”

Editor's Notes

  • #2: Hello everyone, thanks for coming, this session is “Validate your entities with symfony validator and Entity Validation API”
  • #3: I want to thank all the sponsors, because the conference wouldn't be possible without help from sponsors
  • #6: I am software engineer at Ibuildings I work with Drupal since 2011, i am maintainer of different contributed modules: (Paragraphs React : a first integration between ReactJS and Paragraphs contrib module) (jQuery Touch Swipe: a module that implements a system that allow users to flags content in relation to touch events) swipe up..down.., it integrates with the flag contrib module (Paragraphs Wizard : a simple field formatter for paragraphs for generate a multistep wizard)
  • #8: This session will not focus on all the complex structures behind the entity validation system (e.g.: Typed Data API), but on how you as a developer can leverage entity validation to improve your module or site's data integrity.
  • #9: Input validation, also known as data validation, is the proper testing of any input supplied by a user or application. Input validation prevents improperly formed data from entering an information system. 
  • #14: 1. Validates content on multiple levels, you’ll se what those levels are later 2. When it fails it returns a list of violations, if succeeds you get an empty list 3. Happens automatically in entity form validation, so you don’t need to call other methods if you are submitting an entity form
  • #16: JSR 303 (Bean Validation) Simply put it provides an easy way of ensuring that the properties of your objects have the right values in them. This document describes each aspect of the bean validation specification in a separate chapter. One should remember that the specification is a consistent whole. Chapter 2, Constraint Definition describes how constraints are defined. Chapter 3, Constraint declaration and validation process describes how a JavaBean class is decorated with annotations to describe constraints. Chapter 4, Validation APIs describes how to programmatically validate a JavaBean. Chapter 5, Constraint metadata request APIs describes how the metadata query API works.
  • #17: This new validation API has been implemented based on the Symfony validator.
  • #19: An important fact, is that you always get the list of violations even if it’s empty.
  • #20: So, first, you call ->validate() on your entity, then you can call $violations->count() and if the count is higher than zero you know you have a problem. Implements also the \iteratoraggregate so you can simply loop over the violations with a foreach
  • #21: To get a list of Entity level violations we can use the getEntityViolations() method and loop through all of them. Once we have our individual ConstraintViolationInterface instances, we can inspect them for what went wrong. For instance, we can get the error message with getMessage(), the property path that failed with getPropertyPath() and the invalid value with getInvalidValue(), among other useful things.
  • #30: (Src/Plugin/Validation/Constraint, all below this path will be discoverable by drupal) * While core does not prefix constraint plugins, modules have to prefix them * with the module name in order to avoid any naming conflicts; for example, a * "profile" module would have to prefix any constraints with "Profile".
  • #31: No t() needed You can use placeholders
  • #32: It’s the same of the Constraint, Extends the Constraint Class, it allows to pass an array of fields to the validator. /** * Provides a base class for constraints validating multiple fields. * * The constraint must be defined on entity-level; i.e., added to the entity * type. * * @see \Drupal\Core\Entity\EntityType::addConstraint */
  • #34: Inside validate, you don't need to return a value. Instead, you add violations to the validator's context property and a value will be considered valid if it causes no violations. The buildViolation() method takes the error message as its argument and returns an instance of ConstraintViolationBuilder. The addViolation() method call finally adds the violation to the context using messages coming from your constraint. For Dependency Injection you can implement ContainerInjectionInterface.
  • #35: The methods that you’ll use the most are “addViolation” and “buildViolation”, for instance when you need to return a dynamic error message (set a minimum and a maximum of a range….)
  • #36: For instance when validating a node, the context will always be that node, because the validate method is executed on the $node object, if you call validate on a single field, then the context will be that field.
  • #39: The field name vanish from the property path because it becomes the context that i’ve mentioned before.
  • #42: Entity level If you are creating a new ContentEntity type You can set the constraints property into the constraints @ContentEntityType Constraints = {“commentname” = {}}
  • #43: We can provide our own implementation of Hook_entity_type_alter And then ->addConstraint And the options, so for instance my constraint has got an option called “bad” and i want it to have the value 1 For instance you can have a range constraint here and set minimum and maximum value
  • #44: This is how drupal defines the uri baseFieldDefinition of the file entity in the core, BasefieldDefinition has the addConstraint method too
  • #45: Always search for already existing validators rather than always create your own validators
  • #46: This is the code of paragraphs that checks that has an allowed paragraph type
  • #47: Examples of fieldtype are for instance you have entityreference, optionlist, address (this is an example of address module), most of the time you’ll apply validators at entity level but if you create your own fieldtype you might need this. A correct approach for the field type is to use the ValidatoinConstraintManager and return a list of constraints, you can istantiate them using the ->create method of the ConstraintManager and return them in an array. /** * Constraint plugin manager. * * Manages validation constraints based upon * \Symfony\Component\Validator\Constraint, whereas Symfony constraints are * added in manually during construction. Constraint options are passed on as * plugin configuration during plugin instantiation. * You can also use the getDefinitionsByType method of the ConstraintManager to get Constraints by type, so for instance if i’m creating an integer field using validationconstraintmanager i can get all the Constraints that can be applied to an integer field. * Complex data constraint. * * Validates properties of complex data structures.
  • #48: This is from EntityReferenceItem.php (a @FieldType Plugin) , from the entity reference module in the core You are already defining the property and you can call directly addConstraint on the property.
  • #51: This is the reason why i've decided to perform this talk, i was trying to validate a node with a paragraph field
  • #53: Core Validation tests
  • #54: My Advice is to use this, defining constraint in the data architeture is very important so your application won’t blow up just because someone entered wrong data. Any questions ?, thank you very much for listening.