trauma
trauma

Reputation: 322

Symfony2 Add to form many fields with one name

I want to add many hidden files to form builder with one name like an array. For example:

<input type="hidden" name="test[]">
<input type="hidden" name="test[]">
<input type="hidden" name="test[]">
<input type="hidden" name="test[]">

How I can do this? Thanks.

$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
                $form = $event->getForm();

                $photos = $event->getData()->getPhotos();

                if ($photos) {
                    foreach ($photos as $photo) {
                        $form->add('uploadedPhoto', CollectionType::class, array(
                            'entry_type' => HiddenType::class,
    //                        'data' => $photo->getId(),
                            'mapped' => false,
                        ));
                    }
                }
            });

Upvotes: 2

Views: 351

Answers (1)

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3812

You need to use collection type:

use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

$builder->add('foo', CollectionType::class , array('entry_type' => HiddenType::class));

I assume that You want to list as hidden all elements under photos property from data source.

$builder->add('photos', CollectionType::class , array(
    'entry_type' => HiddenType::class, 
    'mapped' => false
));

Read more about this field type: http://symfony.com/doc/current/reference/forms/types/collection.html#entry-type

Upvotes: 2

Related Questions