Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamically add Elements to Symfony Form Collection without Data
<?php
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, []);
$builder->addEventListener(
FormEvents::POST_SET_DATA,
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$contract = $this->contractRepository->find($data->contractId());
foreach ($contract->customFields() as $customField) {
$form
->get('customFields')
->add($customField->getName(), TextType::class, [
'label' => $customField->getLabel()
])
;
}
}
);
}
}
@webdevilopers
Copy link
Author

webdevilopers commented Nov 17, 2016

Came from: https://twitter.com/webdevilopers/status/798593562644533249

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.

@MaximeCertain
Copy link

MaximeCertain commented Apr 25, 2019

awesome
thank's for sharing

@kl3sk
Copy link

kl3sk commented Mar 13, 2020

Thanks just what I need.

@webdevilopers
Copy link
Author

webdevilopers commented Mar 17, 2020

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

@nahuboutet
Copy link

nahuboutet commented Aug 12, 2020

Genius! you saved my day!

@webdevilopers
Copy link
Author

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