Michał Kalinowski
Michał Kalinowski

Reputation: 461

Validation in Symfony2: Entity vs FormType - best practices?

What are the best practices when it comes to putting validation constraints into your projects?

In most cases you keep it in Entities or FormTypes?

What are the pros and cons?

Here is what i mean:

FormType example

$builder
   ->add('firstName', TextType::class, array(
       'constraints' => array(
           new NotBlank(),
       ),
   ))
;

Entity example

class Author
{
    /**
     * @Assert\NotBlank()
     */
    protected $firstName;
}

Upvotes: 0

Views: 483

Answers (1)

Terenoth
Terenoth

Reputation: 2598

My answer is: both.

Sometimes your have constraints that will apply on your Entities application-wide. But sometimes constraints will only apply in your Form context. In that latter case, you can use constraints directly in your Form, or you can use validation_groups.

I tend to use Entity constraints the most, because I find it cleaner and does not introduce inconsistency in my application.

Upvotes: 4

Related Questions