0
votes

I have a problem with form rendering: I would like to define few similar form fields (pass them in array or create in loop) and then I would like to render them in twig in a loop like this:

{% for field in form.collection %}
    <li>
        {{ form_label(field) }}
        {{ form_widget(field) }}
    </li>
{% endfor %}

Reason: I need to have access to label and widget of each field while rendering it in a loop (not knowing name of each field). I seems, that the only way is to have a CollectionType. This is not based on any entity. I have seen the docs with examples with entities, but can the fields be added manually ?

Something like:

class FormcollectionType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
   

        $builder->add('collection', CollectionType::class, [
            // each entry in the array will be an "ChoiceType" field
            'entry_type' => ChoiceType::class,
            // these options are passed to each "collection" type
            'entry_options' => [
                'attr' => ['class' => 'someclass'],
            ],

            // How to define few ChoiceType fields in CollectionType here, manually ?
        ]);

Thank you for any help :)

2

2 Answers

1
votes
$builder->add('favoriteCities', CollectionType::class, [
'entry_type'   => ChoiceType::class,
'entry_options'  => [
    'choices'  => [
        'Nashville' => 'nashville',
        'Paris'     => 'paris',
        'Berlin'    => 'berlin',
        'London'    => 'london',
    ],
],
]);
0
votes

Thanks,

actually, what does the trick is the 'data' field....

so:

         $builder->add('collection', CollectionType::class, [
            'entry_type'   => ChoiceType::class,
            'entry_options' => [
                'attr' => ['class' => 'someclass'],
                'choices'  => [
                    'Nashville' => 'nashville',
                    'Paris'     => 'paris',
                    'Berlin'    => 'berlin',
                    'London'    => 'london',
                ],
            ],
            'data' => ['choice1Field'  => 'choice1', 
                      'choice2Field'  => 'choice2'  ]
                
            ]);