Reputation: 65
I want to accomplish the following:
FormType -> If my checkbox is checked, hide a normally required field and make it required = false, so I can submit my Form.
So I need to override a specific form field if my checkbox is checked. Example...
Form:
$builder->add(
'checkbox',
CheckboxType::class,
[
'label' => 'checkbox',
'required' => false,
'mapped' => false,
'attr' => [
'class' => 'checkbox',
]
]
);
index:
$('.checkbox').change(function () {
if ($('.checkbox').is(':checked')) {
$(".end-date").hide();
} else {
$(".end-date").show();
}
});
how do i continue?
i tried something like this (somehow it's not working):
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
$config = $form->get('what_ever_field')->getConfig();
$options = $config->getOptions();
$form->add(
'what_ever_field',
get_class($config->getType()->getInnerType()),
array_replace(
$options,
[
'required' => false,
]
)
);
});
But it makes no sense because the checkbox and the listener have no relation.
Upvotes: 1
Views: 1023
Reputation: 410
I think it would be much easier to dynamically change the field's required attribute via JS after it's rendered on the page. You're half way there:
JS
$('.checkbox').change(function() {
if ($('.checkbox').is(':checked')) {
$(".end-date").removeAttr("required");
$(".end-date").hide();
} else {
$(".end-date").attr("required","required");
$(".end-date").show();
}
});
This JQuery code can be optimized, but that's about it. Hope it helped.
Upvotes: 2