Vender Aeloth
Vender Aeloth

Reputation: 788

Best practice symfony validation

I'm asking myself about the validation when an user sends a form... I saw the documentation and a tutorial. They explain 2 ways to valid datas:

Documentation:

You have to create the file: /Resources/config/validation.yml

Then add something like that:

Acme\BlogBundle\Entity\Author:
    properties:
        name:
            - NotBlank: ~

Tutorial I saw on Internet:

They add constraints directly in Entity like:

use Symfony\Component\Validator\Constraints as Assert;
  /**
   * @var string $title
   *
   * @ORM\Column(name="title", type="string", length=255)
   * @Assert\MinLength(10)
   */
  private $title;

There is a best pratice? Should I write all constraints in validation.yml or in my entities? Is it possible to face a form without entity behind?

Benefit from separate file: You have all constraints in only one file

Benefit from entity file: You have sql constaints with your form constaints and you have the field type.

So, what should I use? Or no one cares about that?

Edit: I don't find any information about how to add a variable in validation.yml like:

Acme\BlogBundle\Entity\Author:
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: [name]
message: {{ name }} isn't available

In Entity:

@Assert\UniqueEntity(message='{{ name }} isn't available'

Best regards,

Upvotes: 2

Views: 1722

Answers (1)

user3577953
user3577953

Reputation:

Should I write all constraints in validation.yml or in my entities?

You can, but you don't have to, it is more about personal preference. Personally, I prefer to validate input in my forms, like this:

$builder->add('contactPerson', 'text', array(
    'label' => 'Contact person',
    'constraints' => array(
        new NotBlank(array('message' => 'This field can not be empty.'))
    ),
    'required' => true,
));

Is it possible to face a form without entity behind?

Yes it is, but usually it is better to use entity behind. If you want to leave out the entity behind form, you just remove this line from your form's setDefaultOptions method:

'data_class' => '...'

After submitting the form, you can access form data by using $form->getData().

Benefit from separate file: You have all constraints in only one file

Benefit from entity file: You have sql constaints with your form constaints and you have the field type.

So, what should I use? Or no one cares about that?

This is more about personal preference. Personally, I prefer to have validation and form in the same time. Searching for the validation in some other file when I want to make a change to some of my fields in form would take me more time.

Upvotes: 3

Related Questions