dongli2000 2014-01-10 09:25
浏览 22
已采纳

Symfony2根据选项更改表单行为

I have a form that I want to use for both an and edit, but want to change the fields and validation accordingly.

I am changing what the form displays by looking at the 'name' option passed when running the createForm method in the controller.
In controller:

public function createAction(Request $request)
{
    $client = new Client();
    $form = $this->createForm('client', $client, array('name' => 'add'));

    $request = $this->getRequest();

    if ('POST' === $request->getMethod()) {
        $form->handleRequest($request);

        if ($form->isValid()) {
            $client->save();
        }
    }

    return $this->render('Bundle:client:clientAdd.html.twig', array(
        'form' => $form->createView(),
    ));
}

In the ClientType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('id');

    if ('add' === $options['name']) {
        $builder->add('name');
    }

    if ('edit' === $options['name']) {
        $builder->add('age');
    }

    $builder->add('save', 'submit', array(
        'label' => 'Save'
    ));
}

The validation (as defined in my validation.yml) has rules for all fields and it will throw an error for the field in add mode that is not present.
How can I get the validation to be conditional?

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥20 安装 opencv4nodejs 报错
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!