多种形式的相同类型 - Symfony 2 [英] Multiple forms of same type - Symfony 2

查看:115
本文介绍了多种形式的相同类型 - Symfony 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有我的控制器操作类似于这个

  $ task1 = new Task(); 
$ form1 = $ this-> createForm(new MyForm(),$ task1);

$ task2 = new Task();
$ form2 = $ this-> createForm(new MyForm(),$ task2);

假设我的MyForm有两个字段

  // ... 
$ builder-> add('name','text');
$ builder-> add('note','text');
// ...

好像两种形式是相同类型的MyForm在视图中呈现时,它们的字段具有相同的名称和ID(两种形式的'名称'字段共享相同的名称和ID;'note'字段也是如此),因为Symfony可能不会绑定表格数据正确。有没有人知道这个解决方案?

解决方案

  //您的表单类型
class myType extends AbstractType
{
private $ name ='default_name';
...
//生成器等等
...
public function getName(){
return $ this-> name;
}

public function setName($ name){
$ this-> name = $ name;
}

//或者你可以通过构造函数设置它(警告这只是一个猜测)

公共函数__constructor($ formname)
{
$ this-> name = $ formname;
parent :: __ construct();
}

}

  //你控制器

$实体=新实体();
$ request = $ this-> getRequest();

$ formType = new myType();
$ formType-> setName('foobar');
//或new myType('foobar');如果你在构造函数中设置

$ form = $ this-> createForm($ formtype,$ entity);

现在您应该可以为您打包的表单的每个实例设置不同的ID ..应该导致< input type =textid =foobar_field_0name =foobar [field]required =required> 等等。


So I have my controller action similar to this

$task1 = new Task();
$form1 = $this->createForm(new MyForm(), $task1);

$task2 = new Task();
$form2 = $this->createForm(new MyForm(), $task2);

And let's say my MyForm has two fields

//...
$builder->add('name', 'text');
$builder->add('note', 'text');
//...

It seems like since the two forms are of the same type MyForm, when rendered in the views, their fields have the same name and IDs (the 'name' fields of two forms share the same name and id; the same goes for the 'note' fields), because of which Symfony may not bind the forms' data correctly. Does anyone know any solution to this?

解决方案

// your form type
class myType extends AbstractType
{
   private $name = 'default_name';
   ...
   //builder and so on
   ...
   public function getName(){
       return $this->name;
   }

   public function setName($name){
       $this->name = $name;
   }

   // or alternativ you can set it via constructor (warning this is only a guess)

  public function __constructor($formname)
  {
      $this->name = $formname;
      parent::__construct();
  }

}

// you controller

$entity  = new Entity();
$request = $this->getRequest();

$formType = new myType(); 
$formType->setName('foobar');
// or new myType('foobar'); if you set it in the constructor

$form    = $this->createForm($formtype, $entity);

now you should be able to set a different id for each instance of the form you crate.. this should result in <input type="text" id="foobar_field_0" name="foobar[field]" required="required> and so on.

这篇关于多种形式的相同类型 - Symfony 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆