N
N
nord_ua2013-07-19 01:38:36
symfony
nord_ua, 2013-07-19 01:38:36

symfony2 dynamic form validation with collection, depending on fields value

For example, I have a Post document, which can be either a simple post with a collection of paragraphs or a link post. A post can be created as a link and later edited with original content (paragraphs that are a collection)
Post fields: title , is_external , external_url , paragraphs .
A paragraph consists of: title , description . Description is required.

How can I validate form values ​​with the following rules:
If is_external is checked, external_url cannot be empty, and paragraphsmay not be checked at all. Otherwise external_url must be empty, the paragraphs collection must contain at least one entry, all paragraphs must be validated.

How to do it right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
JekaRu, 2013-07-19
@JekaRu

To validate everything in the callback yourself?
symfony.com/doc/current/reference/constraints/Callback.html
Or write custom verification?
symfony.com/doc/current/cookbook/validation/custom_constraint.html
Sorry if I didn't understand something.

V
Vitaly Zhuk, 2013-10-13
@ZhukV

One of the good approaches is to create your own validator, which will validate not a property, but an entire class. symfony.com/doc/current/cookbook/validation/custom_constraint.html The big plus here is that you can then define it as a service if necessary, and inject dependencies into it.
It is also possible to process this check on the FormEvents::SUBMIT event (On >= 2.1 < 2.3 FormEvents::BIND), and if there is an error, then add it yourself addError(new FormError(/**… **/));

N
Nikita Gusakov, 2013-07-19
@hell0w0rd

Why do you need form validation? You must have final model validation.
And in my opinion it would be more correct to divide this into 2 entities, and merge these entities on the sample

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question