Multiple forms of same type - Symfony 2

后端 未结 4 1672
栀梦
栀梦 2020-12-10 04:28

So I have my controller action similar to this

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

$task2 = new Task();
$form2 = $this         


        
相关标签:
4条回答
  • 2020-12-10 05:08

    EDIT: Do not do that! See this instead: http://stackoverflow.com/a/36557060/6268862

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

    Now the first instance of the form on the page will have "my_custom_form_0" as its name (same for fields' names and IDs), the second one "my_custom_form_1", ...

    0 讨论(0)
  • 2020-12-10 05:19

    create a single dynamic name :

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

    your name is always single

    0 讨论(0)
  • 2020-12-10 05:25

    I would use a static to create the name

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

    Then you can create as many as you want without having to set the name everytime.

    0 讨论(0)
  • 2020-12-10 05:32
    // 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.

    0 讨论(0)
提交回复
热议问题