CollectionType with mixed entry_type

1.7k Views Asked by At

In Symfony 3 / PHP 7, I need a form who accept an array of mixed type (string, int and array). "entry_type" param for CollectionType only accept a unique Type. How can I have a mixed type ?

$builder
     ->add('value', CollectionType::class, array(
         'entry_type' => ?,
         'allow_add' => true,
         'allow_delete' => true,
     ));
1

There are 1 best solutions below

2
Pavol Velky On

You could use embed forms. In your custom form type you can define multiple input fields for your need and than use it in your CollectionType.

// src/Form/TagType.php
namespace App\Form;

use App\Entity\Tag;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TagType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('string_field')
            ->add('int_field')
            ->add('whatever_field');
    }
}

Use in as entry_type like this:

 use App\Form\TagType;

 // ...
 $builder
      ->add('multiple_fields_collection', CollectionType::class, [
          'entry_type' => TagType::class,
          'allow_add' => true,
          'allow_delete' => true,
      ]);

More information: https://symfony.com/doc/current/form/form_collections.html