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.
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,
]);
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,
));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With