1

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,
     ));
j08691
  • 204,283
  • 31
  • 260
  • 272
Nivek
  • 11
  • 3
  • You can use a simple TextType, but ... How your user will enter an array in your collection? Probably you should use a transform ... – SilvioQ Sep 23 '19 at 15:45
  • User send me an array from frontend with "random" key/value. Any exemple of a transform who help me ? – Nivek Sep 24 '19 at 06:37
  • How he/she send it? A "random" key/value in a html text input element? An transformer example is this https://symfony.com/doc/current/form/data_transformers.html – SilvioQ Sep 24 '19 at 11:35

1 Answers1

0

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

Pavol Velky
  • 770
  • 3
  • 9
  • Thank's for the reply. I can't used a form with defined field because I do not know what will be in this array. – Nivek Sep 24 '19 at 06:34
  • I think you confuse what 'entry_type' option does. It doesn`t define how data will be transformed. It define a class that describe how the value should be threated and what should be rendered. For your needs you only want one TextType and transformation should be done by yourself in controller or encapsulated in your own class. But this is not job for a Symfony or Symfony forms. $builder->add('field', TextType::class) – Pavol Velky Sep 24 '19 at 18:23