@domenico
To create a new form in Symfony, you can follow these general steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// src/Form/MyFormType.php namespace AppForm; use SymfonyComponentFormAbstractType; use SymfonyComponentFormFormBuilderInterface; use SymfonyComponentOptionsResolverOptionsResolver; class MyFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // Define the form fields // Example: $builder->add('title'); $builder->add('description'); } public function configureOptions(OptionsResolver $resolver) { // Configure the form options // Example: $resolver->setDefaults([ 'data_class' => 'AppEntityMyEntity', ]); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// src/Controller/MyController.php namespace AppController; use AppFormMyFormType; use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentHttpFoundationRequest; use SymfonyComponentRoutingAnnotationRoute; class MyController extends AbstractController { /** * @Route("/my-form", name="my_form") */ public function myFormAction(Request $request) { // Create the form $form = $this->createForm(MyFormType::class); // Handle the form submission $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // Handle the valid form submission // Example: $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($form->getData()); $entityManager->flush(); return $this->redirectToRoute('my_success_page'); } // Render the form template return $this->render('my/form.html.twig', [ 'form' => $form->createView(), ]); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{# templates/my/form.html.twig #} {% extends 'base.html.twig' %} {% block body %} <h1>My Form</h1> {{ form_start(form) }} {{ form_row(form.title) }} {{ form_row(form.description) }} {{ form_row(form.submit) }} {{ form_end(form) }} {% endblock %} |
That's it! Your new form is now ready to use. You can access it by navigating to the URL that corresponds to your controller action.