Symfony Forms

Quick Review: Creating a form in Symfony 5

Creating a form in Symfony 5 is a very simple process, just follow my instructions below. I will guide you in replacing the HTML form we used on our Symfony 4 CRM project.

If you have any questions please do let me know.

  1. Let’s make sure you have the required files on your project, run the following composer command
    1. composer require symfony/form
  2. Now let’s use the built-in template system to create our form
    1. php bin/console make:form
    2. Complete the requested information, I called it NewCustomer and bounded it to our previously created Customer model class.
  3. You can find the new form that was created at:
    1. App\Form\NewCustomerType;
    2. Open the file and review it, it should have all of the model class properties
  4. Change your new customer route to the following:
    1. $customer = new Customer();
      $formNewCustomer = $this->createForm(NewCustomerType::class, $customer, [
      ‘action’ => $this->generateUrl(‘addCustomer’),’method’ => ‘POST’,
      ]);
      return $this->render(‘customer_manager/newCustomer.html.twig’, [
      ‘form’ => $formNewCustomer->createView(),
      ]);
    2. This will tell your controller to generate a new form using the NewCustomerType form class that was generated previously. We are as well telling the system that it is a POST form that will go to the ‘addCustomer’ route once submitted. Finally, we are creating the form view and passing it to the TWIG template file.
  5. Go to your twig template file and remove your old form, add the following command
    1. {{ form(form) }}
    2. Just like that, refresh your new customer route page and make sure that the new form is showing.
  6. This is one of the most basic ways to add a Symfony Form to your application. Don’t forget it stills needs to be styled and most importantly, you need to code in a submit button at your NewCustomerType form class.
error

Enjoy this blog? Please spread the word :)