0

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;
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Best solution is still not to use entities as data objects. Write Data Transfer Objects to avoid a ton of headaches and making forms a lot easier. In this case I can say your answer is indeed correct.
It's simply a data object with getters/setters (POPO), like my ChangeUsernameType has a ChangeUsernameData, it simply holds the old and new username, my type has a repeated type on the new and matches the old against an existing username. Once submitted and valid I simply do $user->setUsername($myDto->getUsername()); and I flush my user. This prevents my entities from getting in an invalid state and even worse, being flushed by accident in this state. It also means that I can shape my forms without being resistricted by my model.
Thanks for the explanations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.