Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active December 26, 2021 09:15
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save webdevilopers/1fb114dcfeeb604bad3a9ce0a9e7b44e to your computer and use it in GitHub Desktop.
Save webdevilopers/1fb114dcfeeb604bad3a9ce0a9e7b44e to your computer and use it in GitHub Desktop.
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

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

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

Genius! you saved my day!

@webdevilopers
Copy link
Author

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