How to create form in Symfony?

Member

by lizzie , in category: PHP Frameworks , 9 months ago

How to create form in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 3 months ago

@lizzie 

Symfony provides a Form component that makes it easy to create and handle forms in your PHP applications. Here's an example of how you can create a form in Symfony:

  1. Create a form class


First, you'll need to create a form class that represents your form. This can be done by extending the SymfonyComponentFormAbstractType class and implementing the buildForm() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;

class MyFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Add form fields here
    }
}


  1. Add form fields


Next, you'll need to add the form fields to your form. This is done by calling the add() method on the $builder object, which represents the form builder:

1
2
3
4
5
6
7
8
9
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class)
        ->add('email', EmailType::class)
        ->add('message', TextareaType::class)
        ->add('submit', SubmitType::class)
    ;
}


  1. Create a form object


Once you have created your form class, you can create a form object by calling the createForm() method on the FormFactory service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use SymfonyComponentFormFormFactoryInterface;

class MyController
{
    public function createForm(FormFactoryInterface $factory)
    {
        $form = $factory->create(MyFormType::class);

        // Render the form
        return $this->render('my_form.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}


  1. Render the form


Finally, you'll need to render the form in a template. This can be done using the form_start(), form_widget(), and form_end() Twig functions:

1
2
3
4
{{ form_start(form) }}
    {{ form_widget(form) }}
    <button type="submit">Send</button>
{{ form_end(form) }}


For more information, you can refer to the Symfony documentation on forms: https://symfony.com/doc/current/forms.html