I try to have a required value depends on radio button
$builder
->add('radio',ChoiceType::class,[
'label' => 'My radio button',
'choices'=>[
'Yes'=>'Yes',
"No"=>"No"
],
"expanded"=>true,
"multiple"=>false,
'required' => true,
'placeholder' => false
])
->add('file input', FileInputType::class, [
'label' => 'put your file',
'mapped' => false,
'required' => true or false // depends on radio button
])
But i can’t find how to do this, i’m a beginner in symfony.
I use Symfony 5
Please if you have an idea i’m listening
2
Answers
There are a few steps you have to implement to achieve this feature.
FormEvents::PRE_SET_DATA
andFormEvents::PRE_SUBMIT
.PRE_SET_DATA
is used for rendering form with existing data. For example: If Radio YES then display the file_input field otherwise another field is rendered in form.PRE_SUBMIT
is used for set field value based on Radio input. You can add logic here. For example: If YES, then set file_input field value.Note: In Symfont form, If you change anything from the js side then it will not work when the form is submitted. That’s why we have to handle the same logic via
FORM EVENTS
You can use JavaScript to handle the change event on the radio buttons and set
required
attribute for the ‘file input’ field accordingly.