多种形式的相同类型 - Symfony 2

0x5*_*94E 12 forms multiple-forms symfony

所以我的控制器动作类似于此

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

$task2 = new Task();
$form2 = $this->createForm(new MyForm(), $task2);
Run Code Online (Sandbox Code Playgroud)

让我们说我的MyForm有两个字段

//...
$builder->add('name', 'text');
$builder->add('note', 'text');
//...
Run Code Online (Sandbox Code Playgroud)

似乎因为两个表单是相同类型的MyForm,当在视图中呈现时,它们的字段具有相同的名称和ID(两个表单的"名称"字段共享相同的名称和id;同样适用于'注意'字段),因为Symfony可能无法正确绑定表单的数据.有谁知道任何解决方案吗?

Fla*_*ask 19

// 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();
  }
Run Code Online (Sandbox Code Playgroud)

}

// 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);
Run Code Online (Sandbox Code Playgroud)

现在你应该可以为你创建的表单的每个实例设置一个不同的id ..这应该导致<input type="text" id="foobar_field_0" name="foobar[field]" required="required>等等.


Sté*_*gne 10

我会使用静态来创建名称

// 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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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


pea*_*mak 6

编辑:不要那样做!请参阅此处: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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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