Talk To Us For FREE

We are in the Business of Support and that starts before you even become a client.
Please prove you are human by selecting the Heart.

How To Define A Symfony 2 Form Type As A Service

Categories : Article, Symfony

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 service - { validation_groups: [Default] } # validation groups - acme_demo.form.type.task: class: AcmeTaskBundleFormTypeTaskType tags: - { 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!

[Total: 0    Average: 0/5]