0

I want to validate form using asserts in Entity class but when I submit the form, it says $form->isValid() is true.

Here is how I got it setup:

// config.yml
validation:      { enabled: true, enable_annotations: false }

// validation.yml
Software\Bundle\Entity\Program:
    properties:
        name:
            - NotBlank: ~

// MyForm
...
        $builder
        ->add('name', 'text', [
            'label' => 'word.name'
        ])
    ;
...

// Program.php

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255, nullable=false)
 */
private $name;

I tried also via Annotations but it did not help. I know I can put 'constraints' property to my form and there set new NotBlank() but I want to have that validation on Entity level since I am going to use an API and I want to have validation in one place instead of two.

Is my validation.yml file ignored or what?

EDIT I did not mention one important thing that my form is embedded into another one. in this case you must use 'cascade_validation' property in your form options.

This answer helped me a lot Symfony2 - Validation not working for embedded Form Type

Community
  • 1
  • 1
undefinedman
  • 620
  • 1
  • 11
  • 25

1 Answers1

0

Your configuration seems correct but your yml is ignored, try to clear your cache.

Also where is your validation.yml ? It must be in a path like : src/AppBundle/Resources/config/validation.yml

In your annotation example, there is no validation constraint you must add @Assert\NotBlank on your property. Nullable = false is only for your database schema.

Symfony doc about validation : http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#using-the-new-validator

Same question about using validation.yml : Symfony2 how to load validation.yml

Community
  • 1
  • 1
HypeR
  • 2,186
  • 16
  • 22
  • It is in src/Software/Bundle/Resources/config folder. I know that my example does not contain @Assert\NotBlank() because I want to use it via .yml file. I only mentioned that I also tried using annotation and that also did not work. – undefinedman Mar 14 '15 at 11:39
  • I even tried the following solution but it did not help http://stackoverflow.com/questions/24064813/how-to-split-validation-yaml-files-in-symfony-2-5 – undefinedman Mar 14 '15 at 12:00
  • 1
    No idea why it's not working, did you try http://stackoverflow.com/a/12368114/3726645 ? or using asserts in your Entity ? – HypeR Mar 16 '15 at 10:04