-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
[Form] How to use expressions in forms without a data class #19720
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
@xabbuh just asking: is this an expected behavior when using expressions in form constraints? I thought the "right way" to solve things like this was using form events. Thanks! |
The solution @pauljura describes looks correct to me if you want to use a form without an underlying class. Though I am not sure where the explanation should be put. https://symfony.com/doc/current/form/without_class.html is probably the best place. |
Thanks to @pauljura! I had the problem that although I have an underlying data class it's the data class of a form collection and neither constraints via Attributes nor configureOptions() worked. The above solution did it, so I appreciate it if you'll add the explanation. Maybe as sub below "Constraints At Class Level" titled "Field dependent constraints" on https://symfony.com/doc/current/form/without_class.html |
Closed by #21043. |
I think it would be worth adding a section on how to use expressions in forms without a data class, because I recently wanted to do this and couldn't find any documentation on it.
A simple example would be a "how did you hear about us?" form, with a selection of radio buttons, and a text input. If the "other" option is chosen, then we want the text input to be non-blank so the user is required to fill something in, otherwise it can remain blank.
The code might look like this:
I guessed at the expression through trial and error, but it works and I think it may come in handy for others.
From my understanding, "this" refers to the current form element, so to get the value of the other form element I have to first go up to the parent, then fetch the element in question, and get its value with getData. Please correct me if this is not right, or not the best way to go about it.
I think this would be handy to include on this page: https://symfony.com/doc/current/form/without_class.html but personally I would not look here first, because I already know how to use forms without a class, I just needed more information on which validator to use and how to configure it.
So I looked here here: https://symfony.com/doc/current/reference/constraints/Expression.html and here: https://symfony.com/doc/current/reference/constraints/When.html but these pages currently assume the validators are being used on an entity, and have no documentation on how to make them work on a form without a data class. So adding some help to these pages would also be useful.
Thanks
The text was updated successfully, but these errors were encountered: