symfony2:如何使更新时不需要表单字段

use*_*311 2 symfony

我有一个带有文件字段的表单,我希望只有在创建记录时才强制使用此字段,而不是在更新时。在 buildForm 我只有这个领域:

->add('file', 'file', array(
            'required'    => false,
        ))
Run Code Online (Sandbox Code Playgroud)

在控制器中,我检查 id 以决定是插入还是更新

谢谢

小智 5

在您的表单类中添加:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setRequired([
        'update',
    ]);
}
Run Code Online (Sandbox Code Playgroud)

然后,当您创建表单时,请使用以下命令:

$form = $this->createForm('formName', $object, array(
            'update' => $entity->getId==null?false:true,
       ));
Run Code Online (Sandbox Code Playgroud)

之后,在您的表单中,在 $options 数组中,您可以使用 $options['update']。例如。:

->add('file', 'file', array(
            'required'    => !$options['update'],
        ))
Run Code Online (Sandbox Code Playgroud)