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条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?
  • ¥15 Ubuntu20.04.4.LTS系统如何下载安装VirtualBox虚拟机?
  • ¥15 如何用QDomDocument读取内容为空格的xml数据
  • ¥15 请阅读下面代码,帮我修改下代码