Symfony2 array of forms?

末鹿安然 提交于 2019-12-03 08:41:15

Just create your forms in array:

$data = $em->findAll();
for ($i = 0; $i < $n; $i++) {
    $forms[] = $this->container
        ->get('form.factory')
        ->createNamedBuilder('form_'.$i, new SomeType, $data)
        ->getForm()
        ->createView();
}

return $this->render(someView, array("forms" => $forms));

UPDATED

As mentioned by edlouth you can create each form named separately. I updated my code.

Create the forms in an array, but give each one a unique name. I've changed it to formbuilder which might not be ideal for you but hopefully something similar will work. I'm also not certain about putting in new SomeType rather than 'form', see http://api.symfony.com/2.4/Symfony/Component/Form/FormFactory.html#method_createNamedBuilder.

$data = $em->findAll();
for ($i = 0; $i < $n; $i++) {

    $forms[] = $this->container
        ->get('form.factory')
        ->createNamedBuilder('form_'.$i, new SomeType, $data)
        ->getForm()
        ->createView();
}

return $this->render(someView, array("forms" => $forms));
Stan Fad

Symfony3:

$datas = $em->findAll();

foreach ($datas as $key=>$data)
{
   $form_name = "form_".$key;
   $form = $this->get('form.factory')->createNamed( 
      $form_name, 
      SomeType::class, 
      $data
   );
   $views[] = $form->createView();
}
return $this->render(someView, ["forms" => $views]);

The action :

$forms = [];

foreach ($articles as $article) {
    $forms[$article->getId()] = $this->get('form.factory')->createNamed(
        'article_'.$article->getId(), // unique form name
        ArticleType::class,
        $article
    );
    $forms[$article->getId()]->handleRequest($request);

    if ($forms[$article->getId()]->isValid()) {
        // do what you want with $forms[$article->getId()]->getData()
        // ...
    }
}

And a better way to render :

return $this->render('some_view.html.twig', [
    'forms' => array_map(function ($form) {
        return $form->createView();
    }, $forms),
]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!