fabtosz
fabtosz

Reputation: 197

Symfony CollectionType field with one default field

I need your advice with CollectionType field.

I've made my collection type field using this: Symfony CollectionType Field
Everything works fine. Even dynamic adding field with JQuery works properly.

But there is an issue.

I can't find out how to add one field each time the collection field renders. Right now after my page loads, my collection field is empty. However, I want the first field from the collection after every page load.

How to achieve this? Should I use Javascript or kind of form event? Any tips for finding a right chapter in documentation or code snippets will be very welcome.

Upvotes: 7

Views: 6031

Answers (3)

SGAmpere
SGAmpere

Reputation: 31

This simply worked for me.

public function buildForm(FormBuilderInterface $builder, array $options) {
    $data = $builder->getData(); // data passed to the form
    $builder->add('textFields', CollectionType::class, [
        'entry_type' => TextType::class,
        'data' => $data ? $data->getTextFields() : ['']
    ]);
}

Upvotes: 1

Pedro Casado
Pedro Casado

Reputation: 1745

This way worked for me.

// 3 default values for empty form
$configArr = [[], [], []];

if ($builder->getData()) {
    $configArr = $builder->getData()->getColumns();
}

$builder->add('columns', CollectionType::class, [
    'entry_type' => ColumnType::class,
    'prototype' => true,
    'allow_add' => true,
    'allow_delete' => true,
    'data' => $configArr,
    'mapped' => false,
]);

Upvotes: 2

OK sure
OK sure

Reputation: 2656

I think I remember hitting this and I ended up creating data with an empty child on first load.

I'm unable to test this however I think the following should work depending on your form specifics.

public function someAction()
{
    $data = [];
    $data['collection_name'][] = ['text' => ''];

    $form = $this->createForm(SomeType::class, $data);

    return $this->templating->renderResponse('template.twig.html', [
        'form' => $form,
    ]);
}

Adding 'required' => false, to the collection's form config should prevent empty items being persisted.

You may also investigate the configureOptions method on the form Type class:

public function configureOptions(OptionsResolver $resolver)
{
    $data = [];
    $data['collection_name'][] = ['text' => ''];
    $resolver->setDefaults(array(
        'empty_data' => $data,
    ));
}

Upvotes: 1

Related Questions