@lew
To render a dynamic Symfony form, you can follow these steps:
Here's an example that demonstrates these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Form Type use SymfonyComponentFormAbstractType; use SymfonyComponentFormExtensionCoreTypeTextType; use SymfonyComponentFormFormBuilderInterface; use SymfonyComponentFormFormEvent; use SymfonyComponentFormFormEvents; class MyFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', TextType::class) ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if ($data && $data->getFieldType() === 'dynamic') { $form->add('dynamicField', TextType::class); } }); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Controller use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentHttpFoundationRequest; class MyController extends AbstractController { public function index(Request $request) { $data = new MyData(); $form = $this->createForm(MyFormType::class, $data); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // Process form data } return $this->render('my-template.html.twig', [ 'form' => $form->createView(), ]); } } |
1 2 3 4 5 |
{# my-template.html.twig #} {{ form_start(form) }} {{ form_widget(form.name) }} {{ form_widget(form.dynamicField) }} {{ form_end(form) }} |
In the example above, the "dynamicField" is added to the form only when the provided data has a "fieldType" attribute set to "dynamic".