Steven Lnds
Steven Lnds

Reputation: 49

Loop in twig for form symfony2

I prog one application for my project.

I have one form for Mesure.

for the moment I have this :

enter image description here

But I want this :

enter image description here

Have you got a suggestion?

My code is :

MesureType :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('date')
    ->add('mesure')
    ->add('stagiaire', EntityType::class, array('class' => 'stbfAdministratifBundle:Stagiaire',
    'choice_label' => function($allChoices, $currentChoiceKey)
    {
        return $allChoices->getNom().' '.$allChoices->getPrenom();
    }
    ,'multiple' => false));
    $builder->add('enregistrer', SubmitType::class);
}

My controler :

public function ajouterAction(Request $request)
    {
    $repository = $this->getDoctrine()
                ->getManager()
                ->getRepository('stbfSportifBundle:ParamPhysiologique');

        $params = $repository->findAll();

        $uneMesure = new Mesure();
        $form = $this->get('form.factory')->create(MesureType::class, $uneMesure);


        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($uneMesure);
            $em->flush();

        }
        return $this->render('stbfSportifBundle:Mesure:ajouter.html.twig', array('form' => $form->createView(), 'param' => $params));
    }

And twig :

{% block body %}
<h1>Page d'ajout d'une mesure pour un stagiaire</h1>

<table>
<tr>
<td>{{ form_widget(form.date) }}</td>
</tr>
<tr>
<td>{{ form_widget(form.stagiaire) }}</td>
</tr>
<tr>
    {% for param in param %}
<td>
    {{param.libelle}} : {{ form_widget(form.mesure) }}</td>
</tr>
{% endfor %}
</table>
{{ form_widget(form.enregistrer, {'attr': {'class': 'btn btn-primary'}}) }}
{% endblock %}

I need you're help, I don't know why my loop don't work.

Thank's for you're help.

Upvotes: 1

Views: 2048

Answers (1)

Hasan Baig
Hasan Baig

Reputation: 511

With reference to your code: first of all try to dump your variable param if you got all the values then change the loop variable i.e. try: {% for param2 in param %}

One more thing: your code is

{% block body %}
<h1>Page d'ajout d'une mesure pour un stagiaire</h1>

<table>
<tr>
<td>{{ form_widget(form.date) }}</td>
</tr>
<tr>
<td>{{ form_widget(form.stagiaire) }}</td>
</tr>
<tr>
    {% for param in param %}
<td>
    {{param.libelle}} : {{ form_widget(form.mesure) }}</td>
</tr>
{% endfor %}
</table>
{{ form_widget(form.enregistrer, {'attr': {'class': 'btn btn-primary'}}) }}
{% endblock %}

your table structure is not correct. Repeat the inside the for loop.

Use this:

{% for param2 in param %}
<tr>
<td>
    {{param2.libelle}} : {{ form_widget(form.mesure) }}</td>
</tr>
{% endfor %}

Upvotes: 2

Related Questions