Home > Back-end >  Symfony - How to show a collection of form inputs with a loop in a twig template?
Symfony - How to show a collection of form inputs with a loop in a twig template?

Time:10-03

I'm a beginner with PHP and Symfony.

I'm trying to show each values of ring (which is entity) from database and trying to add checkbox at the end of the each ring.

My twig template only shows the checkbox in the first ring.

How do I show all the rings?

This is my controller:

public function testPage(Request $request) { 
  $ring = $this->ringRepository->customFindAll();
  $jewel = $this->ringJewelRepository->customFindAll();
  $custom = $this->customRingRepository->customFindAll();
      
  $form = $this->createFormBuilder($ring)
     ->add('active', CheckboxType::class, [
         'label'=>'Selection',
         'required'=>false
     ])
     ->getForm();
   $form->handleRequest($request);
      
   return [
     'rings'=>$ring,
     'jewels'=>$jewel,
     'custom' => $custom,
     'form'=>$form->createView()
   ];
}

This is my Twig template:

{% for ring in rings %}
<div>
  <div >
             
    <p>Ring Name: {{ ring.ring_name }}</p>
            
    <p>Ring Type: {{ ring.ring_type }}</p>
            
    {{ form_start(form) }}
            
    {{ form_widget(form.active) }}
          
    {{ form_end(form) }}   
  </div>
  <div >
    <a href="{{ url('update_ring', {'id': ring.id}) }}" >Update Ring</a>
  </div>
</div>
{% endfor %}

CodePudding user response:

Considering your use-case I think you might be looking for an EntityType, with the 'multiple' option set to true. The syntax would be as below. Make sure to import your Ring class as well.

     ->add('active', EntityType::class, [
                'class'         => Ring::class,
                'multiple'      => true,
                'label'         => 'Selection',
                'required'      => false,
                'query_builder' => static fn (RingRepository $ringRepository) => $ringRepository->customFindAll(),
     ]);

You can read more about the EntityType in the symfony docs.

  • Related