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:

 #src/AppBundle/Resources/config/services.yml

services: 
    app.form.type.task:class:AppBundle\Form\Type\NewsType
       arguments:
          -"@app.my_service"
       tags:
          -{ name: form.type }

#This is the service that you want to pass to the form as a parameter
    app.my_service:
       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);
$form->handleRequest($request);

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

That's it.