12

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

$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 可能无法正确绑定表单的数据。有谁知道这个问题的任何解决方案?

4

4 回答 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>等等。

于 2012-05-12T11:24:09.750 回答
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;
        }
    }

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

于 2013-09-11T03:53:15.330 回答
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”,...

于 2016-05-09T11:53:03.037 回答
0

创建一个动态名称:

const NAME = "your_name";

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

你的名字总是单身

于 2015-10-13T10:25:25.503 回答