Symfony3 createFormBuilder with loop of 'add&#

2019-09-01 02:43发布

问题:

I would like to loop on the add of a custom form in Symfony 3, like:

$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();

The problem is that I get the error :

Attempted to call an undefined method named "createView" of class "Symfony\Component\Form\FormBuilder".

Also if I do like this:

$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();

It overwrite the previous entries.

回答1:

I made it work like this:

$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();

Thanks to this post: How to add a repeated form in a loop symfony2 for the same entity



标签: forms symfony