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 ? ”

More Related Content

What's hot

What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
Simplilearn
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
Attacking and defending GraphQL applications: a hands-on approach
 Attacking and defending GraphQL applications: a hands-on approach Attacking and defending GraphQL applications: a hands-on approach
Attacking and defending GraphQL applications: a hands-on approach
Davide Cioccia
 
Rest API
Rest APIRest API
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
Tchelinux
 
Common gateway interface
Common gateway interfaceCommon gateway interface
Common gateway interface
Anandita
 
Android pentesting
Android pentestingAndroid pentesting
Android pentesting
Mykhailo Antonishyn
 
Login & Registration defect taxonomy v1.0
Login & Registration defect taxonomy v1.0Login & Registration defect taxonomy v1.0
Login & Registration defect taxonomy v1.0
Samer Desouky
 
Cookies
CookiesCookies
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
Kerry Buckley
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Deep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm ModeDeep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm Mode
Ajeet Singh Raina
 
Appium Presentation
Appium Presentation Appium Presentation
Appium Presentation
OmarUsman6
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample application
Anil Allewar
 
Web servers – features, installation and configuration
Web servers – features, installation and configurationWeb servers – features, installation and configuration
Web servers – features, installation and configuration
webhostingguy
 
OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1
OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1
OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1
Ji-Woong Choi
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
Erik van Appeldoorn
 
Mern stack developement
Mern stack developementMern stack developement
Mern stack developement
kalyankumar836878
 
Single page applications
Single page applicationsSingle page applications
Single page applications
Diego Cardozo
 

What's hot (20)

What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Attacking and defending GraphQL applications: a hands-on approach
 Attacking and defending GraphQL applications: a hands-on approach Attacking and defending GraphQL applications: a hands-on approach
Attacking and defending GraphQL applications: a hands-on approach
 
Rest API
Rest APIRest API
Rest API
 
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
APIs, REST e RESTful: O que os programadores precisam saber? - Marcos Echevar...
 
Common gateway interface
Common gateway interfaceCommon gateway interface
Common gateway interface
 
Android pentesting
Android pentestingAndroid pentesting
Android pentesting
 
Login & Registration defect taxonomy v1.0
Login & Registration defect taxonomy v1.0Login & Registration defect taxonomy v1.0
Login & Registration defect taxonomy v1.0
 
Cookies
CookiesCookies
Cookies
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Deep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm ModeDeep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm Mode
 
Appium Presentation
Appium Presentation Appium Presentation
Appium Presentation
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample application
 
Web servers – features, installation and configuration
Web servers – features, installation and configurationWeb servers – features, installation and configuration
Web servers – features, installation and configuration
 
OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1
OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1
OpenStack 인스턴스 간략 사용자_매뉴얼(liberty)_v1
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Mern stack developement
Mern stack developementMern stack developement
Mern stack developement
 
Single page applications
Single page applicationsSingle page applications
Single page applications
 

Similar to Validate your entities with symfony validator and entity validation api

Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3
Ilio Catallo
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Services
ukdpe
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
Ran Wahle
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
SAP ODATA Overview & Guidelines
SAP ODATA Overview & GuidelinesSAP ODATA Overview & Guidelines
SAP ODATA Overview & Guidelines
Ashish Saxena
 
Automated Testing Of Web Applications Using XML
Automated  Testing Of  Web  Applications Using  XMLAutomated  Testing Of  Web  Applications Using  XML
Automated Testing Of Web Applications Using XML
diongillard
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
MongoDB
 
Il 09 T3 William Spreitzer
Il 09 T3 William SpreitzerIl 09 T3 William Spreitzer
Il 09 T3 William Spreitzer
wspreitzer
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoAgile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Moldova ICT Summit
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
Fermin Galan
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 
Distributed System by Pratik Tambekar
Distributed System by Pratik TambekarDistributed System by Pratik Tambekar
Distributed System by Pratik Tambekar
Pratik Tambekar
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
vrluckyin
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
icubesystem
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
Eyal Vardi
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
GeeksLab Odessa
 

Similar to Validate your entities with symfony validator and entity validation api (20)

Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Services
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
SAP ODATA Overview & Guidelines
SAP ODATA Overview & GuidelinesSAP ODATA Overview & Guidelines
SAP ODATA Overview & Guidelines
 
Automated Testing Of Web Applications Using XML
Automated  Testing Of  Web  Applications Using  XMLAutomated  Testing Of  Web  Applications Using  XML
Automated Testing Of Web Applications Using XML
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
 
Il 09 T3 William Spreitzer
Il 09 T3 William SpreitzerIl 09 T3 William Spreitzer
Il 09 T3 William Spreitzer
 
Spring training
Spring trainingSpring training
Spring training
 
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoAgile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai Shevchenko
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
 
Distributed System by Pratik Tambekar
Distributed System by Pratik TambekarDistributed System by Pratik Tambekar
Distributed System by Pratik Tambekar
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 

Recently uploaded

PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
obonagu
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
introduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdfintroduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdf
ravindarpurohit26
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
PauloRodrigues104553
 
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
skuxot
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
bhadouriyakaku
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
zwunae
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 

Recently uploaded (20)

PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
introduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdfintroduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdf
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
 
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 

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

  1. Hello everyone, thanks for coming, this session is “Validate your entities with symfony validator and Entity Validation API”
  2. I want to thank all the sponsors, because the conference wouldn't be possible without help from sponsors
  3. 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)
  4. 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.
  5. 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. 
  6. 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
  7. 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.
  8. This new validation API has been implemented based on the Symfony validator.
  9. An important fact, is that you always get the list of violations even if it’s empty.
  10. 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
  11. 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.
  12. (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".
  13. No t() needed You can use placeholders
  14. 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 */
  15. 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.
  16. 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….)
  17. 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.
  18. The field name vanish from the property path because it becomes the context that i’ve mentioned before.
  19. Entity level If you are creating a new ContentEntity type You can set the constraints property into the constraints @ContentEntityType Constraints = {“commentname” = {}}
  20. 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
  21. This is how drupal defines the uri baseFieldDefinition of the file entity in the core, BasefieldDefinition has the addConstraint method too
  22. Always search for already existing validators rather than always create your own validators
  23. This is the code of paragraphs that checks that has an allowed paragraph type
  24. 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.
  25. 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.
  26. This is the reason why i've decided to perform this talk, i was trying to validate a node with a paragraph field
  27. Core Validation tests
  28. 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.