我想完成以下工作:
FormType -> If my checkbox is checked, hide a normally required field and make it required = false, so I can submit my Form. 因此,如果选中了复选框,则需要重写特定的表单字段。例如..。
表格:
$builder->add(
'checkbox',
CheckboxType::class,
[
'label' => 'checkbox',
'required' => false,
'mapped' => false,
'attr' => [
'class' => 'checkbox',
]
]
);索引:
$('.checkbox').change(function () {
if ($('.checkbox').is(':checked')) {
$(".end-date").hide();
} else {
$(".end-date").show();
}
});我该怎么继续?
我试过这样的方法(不知怎么不管用):
$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,
]
)
);
});但这是没有意义的,因为复选框和听者之间没有任何关系。
发布于 2018-01-25 15:36:17
我认为,在页面上呈现字段后,通过JS动态更改字段的必需的属性要容易得多。你已经走到一半了
JS
$('.checkbox').change(function() {
if ($('.checkbox').is(':checked')) {
$(".end-date").removeAttr("required");
$(".end-date").hide();
} else {
$(".end-date").attr("required","required");
$(".end-date").show();
}
});这个JQuery代码可以优化,但仅此而已。希望能帮上忙。
https://stackoverflow.com/questions/48445366
复制相似问题