I use Symfony 5.3. I have a form with 3 fields that are not mapped to any entity:
- "reason" - text,
- "use_predefined" - checkbox
- "predefined_reason" - dropdown.
I build the form like this (a fragment):
...
public function build(FormBuilderInterface $builder)
{
$builder->add('reason', TextareaType::class, [
'label' => 'Reason',
'required' => true,
'mapped' => false,
]);
$builder->add('use_predefined',
CheckboxType::class, [
'label' => 'Use predefined reason',
'required' => false,
'mapped' => false,
]);
$builder->add(
'predefined_reason',
ChoiceType::class,
[
'choices' => [
'option 1' => 1,
'option 2' => 2,
'option 3' => 3,
'option 4' => 4,
],
'expanded' => false,
'mapped' => false,
'label' => 'some label',
'required' => false,
]
);
}
...
"reason" field should displayed in the UI as required, but other two should not. However during the validation if checkbox "predefined_reason" is checked, the first field should not be required, and "predefined_reason" - should.
You should be able to use Expression to assert if your property are valid.
Don't forget to edit your form and remove required field if unnecessary since they will be verified in form validation.
If you want something more dynamic, you may have to use javascript.
You could also create a custom contraint to do something similar.