Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 956
fabtosz Avatar asked Aug 21 '17 13:08

fabtosz


2 Answers

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,
]);
like image 86
Pedro Casado Avatar answered Oct 17 '22 20:10

Pedro Casado


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,
    ));
}
like image 22
OK sure Avatar answered Oct 17 '22 20:10

OK sure