-
-
Save mablae/ef7abbf2c1d0c8c7bc1606c686c0b98c 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() | |
]) | |
; | |
} | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment