Menu Close
    Hire Us Request Quote Reading List Switch to Dark Mode

    Symfony Validation Groups

    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

    . . .

    Comment (1)

    Add Your Comment

  • sk1
    Nice Article
  • Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close