Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Dynamically add Elements to Symfony Form Collection without Data
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
final class RecordResult extends AbstractType
private $contractRepository;
public function __construct($contractRepository) {
$this->contractRepository = $contractRepository;
* @param FormBuilderInterface $builder
* @param array $options
public function buildForm(FormBuilderInterface $builder, array $options)
$builder->add('customFields', CollectionType::class, []);
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$contract = $this->contractRepository->find($data->contractId());
foreach ($contract->customFields() as $customField) {
->add($customField->getName(), TextType::class, [
'label' => $customField->getLabel()
Copy link

webdevilopers commented Nov 17, 2016

Came from:

This was the final solution that worked out for me @rendler-denis. Since I had to add the custom field elements even if no data was present, I had to use the POST_SET_DATA event.

Copy link

MaximeCertain commented Apr 25, 2019

thank's for sharing

Copy link

kl3sk commented Mar 13, 2020

Thanks just what I need.

Copy link

webdevilopers commented Mar 17, 2020

Some years old but still seems to work and help. You're welcome @MaximeCertain, @kl3sk.

Copy link

nahuboutet commented Aug 12, 2020

Genius! you saved my day!

Copy link

webdevilopers commented Aug 13, 2020

You're welcome @nahuboutet .

Actually I'm suprised this 4-year-old code still works. The form component is changing frequently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment