Description
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:
$builder
->add('how_did_you_hear', ChoiceType::class, [
'required' => true,
'label' => 'How did you hear about us?',
'choices' => [
'Search engine' => 'search_engine',
'Friends' => 'friends',
'Other' => 'other',
],
'expanded' => true,
'constraints' => [
new Assert\NotBlank(),
]
])
->add('other_text', TextType::class, [
'required' => false,
'label' => 'Please specify',
'constraints' => [
new Assert\When(
expression: 'this.getParent().get("how_did_you_hear").getData() == "other"',
constraints: [
new Assert\NotBlank(),
],
)
],
])
;
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