Last active
December 26, 2021 09:15
-
-
Save webdevilopers/1fb114dcfeeb604bad3a9ce0a9e7b44e to your computer and use it in GitHub Desktop.
Dynamically add Elements to Symfony Form Collection without Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() | |
]) | |
; | |
} | |
} | |
); | |
} | |
} |
Genius! you saved my day!
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
Some years old but still seems to work and help. You're welcome @MaximeCertain, @kl3sk.