Symfony3 createFormBuilder循环为'添加'

时间:2016-03-24 14:40:16

标签: forms symfony

我想在Symfony 3中添加自定义表单,例如:

$defaultData = array('message' => 'Type your message here');
$profilForm = $this->createFormBuilder($defaultData)
    ->add('Nom', TextType::class);
    ->add('Description', TextType::class)

foreach ($variable as $key => $value)
{
    $profilForm
        ->add('Widget', ChoiceType::class, array(
        'choices' => array(
            'Créer' => 'C',
            'Afficher' => 'R',
            'Modifier' => 'U',
            'Supprimer' => 'D'),
        'multiple' => true,
        'expanded' => true))
}
$profilForm
    ->add('send', SubmitType::class)
    ->getForm();

问题是我收到错误:

  

尝试调用名为" createView"的未定义方法。类" Symfony \ Component \ Form \ FormBuilder"。

如果我喜欢这样:

$defaultData = array('message' => 'Type your message here');
$profilForm = $this->createFormBuilder($defaultData)
    ->add('Nom', TextType::class);
    ->add('Description', TextType::class)

foreach ($variable as $key => $value)
{
    $profilForm = $this->createFormBuilder($defaultData)
        ->add('Widget', ChoiceType::class, array(
        'choices' => array(
            'Créer' => 'C',
            'Afficher' => 'R',
            'Modifier' => 'U',
            'Supprimer' => 'D'),
        'multiple' => true,
        'expanded' => true))
}
$profilForm
    ->add('send', SubmitType::class)
    ->getForm();

它会覆盖之前的条目。

2 个答案:

答案 0 :(得分:0)

我让它像这样工作:

$tmpForm = $this->createFormBuilder()
    ->add('Nom', TextType::class)
    ->add('Description', TextType::class);

$i = 2;
foreach ($listWidget as $key => $widget)
{
    $name = preg_replace("/[^a-zA-Z0-9]/", "", $widget->getNom());
    $formBuilder = $this->get('form.factory')->createNamedBuilder($i++, FormType::class, null); 
    $formBuilder
        ->add($widget->getNom(), ChoiceType::class, array(
        'choices' => array(
            'Créer' => 'C',
            'Afficher' => 'R',
            'Modifier' => 'U',
            'Supprimer' => 'D'),
        'multiple' => true,
        'expanded' => true));
    $testForm->add($formBuilder);
}
$tmpForm->add('send', SubmitType::class);
$profilForm = $tmpForm->getForm();

感谢此帖:How to add a repeated form in a loop symfony2 for the same entity

答案 1 :(得分:-1)

我有这个解决方案,对于“ -add”上的foreach来说更干净。

$form = $this->createFormBuilder();
        foreach ($activites as $activite){
            $form = $form
                ->add("1". '_isOk', CheckboxType::class)
                ->add("1". '_commentaire', CheckboxType::class);
        }
        $form = $form->getForm();
        $form->handleRequest($request);
        return $this->render('fiche_proprete/new.html.twig',[
            'form' => $form->createView()
        ]);