如何更改Symfony表单类型选项?
我有此表单类型,
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field1', TextType::class)
->add('field2', TextType::class, [
'required' => true
])
;
}
我想根据字段1将“ field2”所需属性更改为false。我要做的事情:
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if(array_key_exists('field1', $data) && $data['field1'] === 'some value') {
//here I need something to set field2 required option to false
}
});
这样,如果我在field1中键入“一些值”并且提交表格,则field2不再是强制性的。
有可能实现吗?
另外,是否可以为此目的使用正确的事件吗?
I have this form type
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field1', TextType::class)
->add('field2', TextType::class, [
'required' => true
])
;
}
I would like to change the field2 required attribute to false, depending on field1. What I am trying to do:
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if(array_key_exists('field1', $data) && $data['field1'] === 'some value') {
//here I need something to set field2 required option to false
}
});
in this way if I type "some value" in field1 and I submit the form, field2 is no longer mandatory.
Is it possible to achieve that?
Also, is it PRE_SUMBIT the correct event to use for this purpose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所需的仅是HTML属性(并且取决于您的视图将调用客户端验证或更改渲染)。
如果您依靠这一点,那么最好验证实体本身。
为此,您可以使用回调断言。参见 https://symfony.com/symfony.com/doc/doc/current /reference/constraints/callback.html#the-callback-method 有关详细信息。
The required is only a html attribute (and depending on your view will invoke clientside validation, or change rendering).
If you depend on this then it would be better to validate the entity itself.
For this you can use the Callback Assert. see https://symfony.com/doc/current/reference/constraints/Callback.html#the-callback-method for details.