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

问题描述 投票:12回答:4

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

$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;同样适用于'注意'字段),因为Symfony可能无法正确绑定表单的数据。有谁知道任何解决方案吗?

forms symfony multiple-forms
4个回答
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();
  }

}

// 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>等等。


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;
        }
    }

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


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;
    }
}

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


0
投票

创建一个动态名称:

const NAME = "your_name";

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

你的名字总是单身

© www.soinside.com 2019 - 2024. All rights reserved.