monkeyUser
monkeyUser

Reputation: 4679

Use Validation in FormType or in Entity / Yaml

Which Differents are when use Validation Entity or in Yaml or in FormType?

form Type

    ....
    ->add('email', 'text', array (
                    'constraints' => array (
                        new Email(array('message' => 'error Email'))
                    )
                ))
....

YAML

properties:
    email:
        - Email:
            message: error Email.

Entity

{
    /**
     * @Assert\Email(
     *     message = "error Email",
     * )
     */
     protected $email;
}

All These methods are the same ?

Upvotes: 1

Views: 849

Answers (3)

mkmuss
mkmuss

Reputation: 61

Is there a way to use the same validation.yml so the constraints applied to entites are applied to the formtype as well

for instance, if title field in entity is 50charsm ax length, title field in formttype as well.

so we can avoid specifying max length in the add-method of the formtype.

In summary

how to use entity validation constraint in formtype so same constraitn ( required max length ) etc are auto applied ?

Upvotes: 0

Martin Fasani
Martin Fasani

Reputation: 823

I think they would apply the same validation constraints.

I tend to keep all constraints in validation.yml because in my point of view is the most clean way to do it. Also more compatible with Translations.

But all depends on the context and the project you are working on.

UPDATE: After reading Riska's entry I agree with him. The result at the end is the same, but he has the right point there.

Upvotes: 2

Andras
Andras

Reputation: 692

They are not the same! You mixed up entity validation and form validation:

  • Entity validation belong to entities. This means that it isn't matter whether the new data come from a form or ajax query or you just set some constant data. Validation is triggered by calling a validation on the entity. Note: entity validation runs on form validation too.
  • Form validation belong to forms. This means that you can validate form values with them (on calling $form->isValid()). But this can result invalid entities because nothing guarantees that your entities will be consistent (just the forms).

For this reason Symfony recommends using entity validation instead of form validators.

Apart from that, there is no difference among annotation, yml, xml or php format. Only the precedences.

Upvotes: 2

Related Questions