How To Define A Symfony 2 Form Type As A Service

There is no deny that Symfony is a well established and widely used open source web application framework for building enterprise-level applications. Today more ‘n’ more businesses are leveraging from Symfony Development India to get robust and secure web and business applications.
In this blog post, we will see how to define a Symfony 2 form type as a service and call them in your controller. Also, you can easily use that form in other model or service classes outside the controller. The typical way of defining a Symfony 2 form type as a service is:

# src/Acme/TaskBundle/Resources/config/services.yml
services:acme_demo.form.type.task: class: AcmeTaskBundleFormTypeTaskType tags:-
 { name: form.type, alias: task }

// src/Acme/TaskBundle/Controller/DefaultController.php
// ...public function newAction()
$task = ...; $form = $this->createForm( 'task', $task ); // ...
Add the following to your services config file in order to use Symfony 2 form factory to create the form in the service container.
If you are using YAML:

# src/Acme/TaskBundle/Resources/config/services.yml
services acme_demo.form.task: factory_method: createNamed factory_service: form.factory
 class: SymfonyComponentFormForm
 - task_form # name of the form
 - task # alias of the form type
 - null # data to bind, this is where your entity could go #if you have that defined as a
 - { validation_groups: [Default] } # validation groups
 - acme_demo.form.type.task:
 class: AcmeTaskBundleFormTypeTaskType
 - { name: form.type, alias: task }

   task_form  task  null    Default  

Now you can call your form in the controller

// src/Acme/TaskBundle/Controller/DefaultController.php// ...public function newAction()
{ $task = ...; $form = $this->get( 'acme_demo.form.task' );// set initial form data if needed 
$form->setData( $task );}

You can call the form and inject it in other services wherever you have the service container as you wish or you can do it with a class that handles form submission!

In search for strategic sessions?
Let us understand your business thoroughly and help you strategies your digital product..
Book a session