Skip to content

Commit 9f0c2f1

Browse files
committed
Book/Form : Adding a new section about defining forms as service
| Q | A | ------------- | --- | Doc fix? | no | New docs? | yes | Applies to | all | Fixed ticket | -
1 parent ab1a1fa commit 9f0c2f1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

book/forms.rst

+72
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,78 @@ form "type"). It can be used to quickly build a form object in the controller::
833833
// ...
834834
}
835835

836+
.. tip::
837+
838+
Defining your form as a service is a good practice and make it easily usable in
839+
your application. First, you must tag your form as a form type in the service container:
840+
841+
.. configuration-block::
842+
843+
.. code-block:: yaml
844+
845+
# src/Acme/TaskBundle/Resources/config/services.yml
846+
services:
847+
acme_demo.form.type.task:
848+
class: Acme\TaskBundle\Form\Type\TaskType
849+
tags:
850+
- { name: form.type, alias: task }
851+
852+
.. code-block:: xml
853+
854+
<!-- src/Acme/TaskBundle/Resources/config/services.xml -->
855+
<service id="acme_demo.form.type.task" class="Acme\TaskBundle\Form\Type\TaskType">
856+
<tag name="form.type" alias="task" />
857+
</service>
858+
859+
.. code-block:: php
860+
861+
// src/Acme/TaskBundle/Resources/config/services.php
862+
use Symfony\Component\DependencyInjection\Definition;
863+
864+
$container
865+
->setDefinition('acme_demo.form.type.task', new Definition(
866+
'Acme\TaskBundle\Form\Type\TaskType'
867+
)
868+
->addTag('form.type', array(
869+
'alias' => 'task',
870+
))
871+
;
872+
873+
That's it! Now you can use your form directly in a controller::
874+
875+
// src/Acme/TaskBundle/Controller/DefaultController.php
876+
877+
public function newAction()
878+
{
879+
$task = ...;
880+
$form = $this->createForm('task', $task);
881+
882+
// ...
883+
}
884+
885+
or even use it as a normal type in another form::
886+
887+
// src/Acme/TaskBundle/Form/Type/ListType.php
888+
namespace Acme\TaskBundle\Form\Type;
889+
890+
use Symfony\Component\Form\AbstractType;
891+
use Symfony\Component\Form\FormBuilderInterface;
892+
893+
class ListType extends AbstractType
894+
{
895+
public function buildForm(FormBuilderInterface $builder, array $options)
896+
{
897+
// ...
898+
899+
$builder->add('task', 'task');
900+
// Note that the property ``task`` (first argument) is defined as a ``task`` form type (second).
901+
}
902+
903+
// ...
904+
}
905+
906+
Read :ref:`form-cookbook-form-field-service` for more information.
907+
836908
Placing the form logic into its own class means that the form can be easily
837909
reused elsewhere in your project. This is the best way to create forms, but
838910
the choice is ultimately up to you.

0 commit comments

Comments
 (0)