Quantcast
Channel: PHP, Symfony and Myself » symfony 2
Viewing all articles
Browse latest Browse all 5

Intro to symfony2 validation

$
0
0

In this post, we will go through the simplest way of creating symfony2 validation (server side).
Although once you are done with creating your forms in symfony2, there will be an automatic client side (HTML 5) validation which you can control, however, it is highly recommended that you always validate on the server side. I will discuss the validator service in a different post, however, I want to make sure that you can at least complete you first form validator quickly.

I will be referring to the previous post, where we created our first formType and rendered the form in a template. The first thing I want to do is to verify that the HTML5 validation is working and then disable it to check the server side validation. If you have followed my previous posts, you should have a working form where the user can enter details about a music album. If you do not enter a name and hit save, you will get the below error message:

HTML 5 Validation

HTML 5 Validation

There are several ways where you can disable this kind of client side validation. The easiest is to specify if validation is required for your field when creating your form type.

To remind you of code from out AlbumType, I am pasting it below:

class AlbumType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add("name","text",array("label"=>"Album Name",))
            ->add("artist","text")
            ->add("description","text")
            ->add("year","text")
            ->add("save","submit");
    }

Look at all of our fields, we never mentioned that we do not need front-end validation, which can be configured in the third argument which is the options array. I will change the first form entity (name) and disable the validation.

class AlbumType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add("name","text", array(
                    "label"=>"Album Name",
                    "required"=>false,
                    )
                )
            ->add("artist","text")
            ->add("description","text")
            ->add("year","text")

Now that I have revised the code to only include the “required” key in the options array, the front end validation should be disabled. Let us refresh our Album page and try to create an album without entering a name.
It works!!
Now is ignored the name field and jumped to the artist field, which by now , you should know how to disable its validation.

Disable Front-end validation

Disable Front-end validation

Go ahead and add the required key to all the fields in the formType to disable the validation.

class AlbumType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add("name","text",
                array(
                    "label"=>"Album Name",
                    "required"=>false,
                    )
                 )
            ->add("artist","text",
                array(
                  "required"=>false
                   )
                 )
            ->add("description","text",
                array(
                    "required"=>false
                ))
            ->add("year","text",
                array(
                    "required"=>false
                ))
            ->add("save","submit");
    }

You need to be careful wow that we have disabled the front end validation as submitting the form will cause some errors (mysql errors).
Let us now create our Symfony 2 server side validation. You will be surprised how easy and powerful this component is.

A validator is nothing but a check that Symfony2 does based on the developer constraint definition. For example, in our form, we want to define that the name field should not be empty, otherwise we should return an error.

There are different ways of creating the validation and I will be using the yaml format way.
Create the “validation.yml” file in the Resources/config” directory.

validation.yml

validation.yml

In that file, we will define our constraints in a yml format. All what we need to do is to provide the namespace of the entity that we wish to validate and define the validation constraints.

Ziad\Demo\MusicStoreBundle\Entity\Album:
    properties:
        name:
            - NotBlank: ~

That was really easy !! wasn’t it?
To verify, clear your cach by going to your terminal to your project directory and run:
app/console ca:cl (shortcut for clearing the cache)

Once the cache is clear, refresh your page and submit an empty form and you should get an error message saying that the name field can not be blank.

Sumfony2 Validator

Sumfony2 Validator

To know more on what constraints you can define, I suggest you look into this documentation.
These constraints are very easy to use, just the same way we used the”NotBlank” constraint.

Finally, in our controller, we checked if the $form->isValid. If any constraints fails in our validation process, the form will considered to be invalid and hence that what we were doing in our controller.

if ($form->isValid()){
            $em = $this->getDoctrine()->getManager();
            $em->persist($album);
            $em->flush();
            return $this->redirect($this->generateUrl("album_index"),302);
        }

Follow me on twitter(@zjammal) to receive new posts updates!
Ziad

The post Intro to symfony2 validation appeared first on PHP, Symfony and Myself.


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images