YML validation file is ignored

10,077

Did you enable validation in app/config/config.yml ?

...

framework:
    ...
    validation:    { enabled: true }
    ...

...

and if you want to define validation with annotations too, you have to both enable validation and annotation validation :

...

framework:
    ...
    validation:    { enabled: true, enable_annotations: true }
    ...

...

And then don't forget clear the app/cache directory.

Share:
10,077
nikolas
Author by

nikolas

Student of computer science and mathematics

Updated on June 04, 2022

Comments

  • nikolas
    nikolas almost 2 years

    I am new to the Symfony 2 web framework, and am struggling with a very basic validation task. I have an entity model Post that has a member slug, which I use to build the link to the post. In Post.orm.yml I defined unique: true and want to include this constraint as a validator as well.

    I have created a file validation.yml:

    # src/OwnBundles/BlogpostBundle/Resources/config/validation.yml
    
    OwnBundles\BlogpostBundle\Entity\Post:
        properties:
            slug:
                - NotBlank: ~
        constraints:
            - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: slug
    

    The creation function in my controller is quite simple:

    public function addAction(Request $request)
    {
        $post = new Post();
        $form = $this->createForm(new PostType(), $post);
    
        if($request->getMethod() == 'POST')
        {
            $form->bind($request);
            if($form->isValid())
            {
                $em = $this->getDoctrine()->getManager();
                $em->persist($post);
                $em->flush();
                return $this->redirect(
                    $this->generateUrl('own_bundles_blogpost_homepage')
                );
            }
        }
        return $this->render(
            'OwnBundlesBlogpostBundle:Default:add.html.twig',
            array(
                'title' => 'Add new blogpost',
                'form' => $form->createView(),
            )
        );
    }
    

    The basic pageflow works fine, I can add posts and see them, but if I duplicate a post title to test my validation, it throws an exception: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'duplicate-slug' for key 'UNIQ_FAB8C3B3989D9B62'. I have been scanning through documentation for quite some time now, but I was not able to find out why my $form->isValid() returns true.