Symfony Validation Groups – In Symfony, normally we can validate user submitted values against our entities through these ways – Annotation, Yaml, PHP etc. Example validation.yml for product entity
Webkul\DemoBundle\Entity\Product:
properties:
name:
- NotBlank: { message: "product.name.not_blank" }
- Length:
max: 50
maxMessage: "product.name.length"
description:
- Length:
max: 200
maxMessage: "product.description.length"
But when a from or entity used more than one places to create form like Product in any e-commerce
- At time of product add you would never validate product id because it isn’t created yet.
- But at time of edit product, you do.
Then how is form/ entity going to tell Symfony that we need to validate id or not in current request ? For this we use Validation Groups . We declare validation groups in our from and with properties declared in validation.yml.
Controller (It will be array)
$form = $this->createForm(new Product(), $product , array(
'validation_groups' => array('productEdit')
)
);
Yaml (Let’s say you added one validation group for product create form – “product”)
Webkul\DemoBundle\Entity\Product:
properties:
productId:
- NotBlank: { groups: [productEdit] }
name:
- NotBlank: { groups: [product, productEdit] }
- Length:
max: 50
maxMessage: "product.name.length"
groups: [product, productEdit]
description:
- Length:
max: 200
maxMessage: "product.description.length"
groups: [product, productEdit]
Now productId validation is enabled only for Product Edit form.
Framework used – Symfony 2.7, Official Doc
1 comments