Symfony Declare Form as a Service and Instatiate with Constructuctor Arguments

How to create a form with constructor arguments, define it as a service and create form in controller

To pass parameters to a Form Type constructor you need to define it as a service. Let's say that one of this parameters is another service. So first create the form itself:

namespace AppBundle\Form\Type;

use App\Services\MyCustomService;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class NewsType extendsAbstractType

private $myCustomService;

public function __construct(MyCustomService $service)
    $this->myCustomService = $service;

public function buildForm(FormBuilderInterface $builder, array $options)
   // Your code

Then define services in configuration. The form should have the tag name: form.type and have declare the service it wants to use as an argument:


          -{ name: form.type }

#This is the service that you want to pass to the form as a parameter
       class: AppBundle\Services\MyCustomService

To create the form in the controller you do not have to pass the service it uses becauseit is already defined in the services.yml file configuration file. Just create it in the controller like this:

// Some action in your controller
$form = $this->createForm(NewsType::class);

if (!$form->isSubmitted() || !$form->isValid()) {
   return ['form' => $form->createView()];

That's it.