symfony2:如何制作更新时不需要的表单字段
symfony2: how to make a form field not required on update
我有一个带有文件字段的表单,我希望仅在创建记录时而不是在更新时将此字段设置为必填字段。
在 buildForm 中,我只有这个字段:
->add('file', 'file', array(
'required' => false,
))
在控制器中我检查 id 来决定是插入还是更新
谢谢
处理这个问题的正确方法是使用 FormEvents http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html
在您的表单中 class 添加:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setRequired([
'update',
]);
}
然后,当你创建表单时使用这个:
$form = $this->createForm('formName', $object, array(
'update' => $entity->getId==null?false:true,
));
然后,在您的表单中,您可以在 $options 数组中使用 $options['update']。
例如:
->add('file', 'file', array(
'required' => !$options['update'],
))
我有一个带有文件字段的表单,我希望仅在创建记录时而不是在更新时将此字段设置为必填字段。 在 buildForm 中,我只有这个字段:
->add('file', 'file', array(
'required' => false,
))
在控制器中我检查 id 来决定是插入还是更新
谢谢
处理这个问题的正确方法是使用 FormEvents http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html
在您的表单中 class 添加:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setRequired([
'update',
]);
}
然后,当你创建表单时使用这个:
$form = $this->createForm('formName', $object, array(
'update' => $entity->getId==null?false:true,
));
然后,在您的表单中,您可以在 $options 数组中使用 $options['update']。 例如:
->add('file', 'file', array(
'required' => !$options['update'],
))