同一类型的多种形式 - 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(两个表单的"name"字段共享相同的名称和id;"注释"字段也是如此),因此Symfony可能无法正确绑定表单的数据。有谁知道有什么解决方案吗?

// 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);

现在你应该能够为你箱子的每个表单实例设置一个不同的ID..这应该会导致<input type="text" id="foobar_field_0" name="foobar[field]" required="required>等等。

我会使用静态来创建名称

// your form type
    class myType extends AbstractType
    {
        private static $count = 0;
        private $suffix;
        public function __construct() {
            $this->suffix = self::$count++;
        }
        ...
        public function getName() {
            return 'your_form_'.$this->suffix;
        }
    }

然后,您可以根据需要创建任意数量的名称,而无需每次都设置名称。

编辑:不要那样做!请改为查看以下内容:http://stackoverflow.com/a/36557060/6268862

在Symfony 3.0中:

class MyCustomFormType extends AbstractType
{
    private $formCount;
    public function __construct()
    {
        $this->formCount = 0;
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        ++$this->formCount;
        // Build your form...
    }
    public function getBlockPrefix()
    {
        return parent::getBlockPrefix().'_'.$this->formCount;
    }
}

现在,页面上表单的第一个实例将以"my_custom_form_0"作为其名称(字段的名称和ID相同),第二个实例为"my_custom_form_1",...

创建一个动态名称:

const NAME = "your_name";
public function getName()
{
    return self::NAME . '_' . uniqid();
}

你的名字总是单一的