Editing
Symfony Forms Cookbook
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
[[Category:Symfony]] [[Category:PHP]] [[Category:Web Development]] == Basic form building == Build a form object and render it in a template from within a controller:<ref>[http://symfony.com/doc/current/book/forms.html#building-the-form Building The Form], Symfony forms documentation</ref> <syntaxhighlight lang="php" highlight="6,17-21,24"> // src/AppBundle/Controller/DefaultController.php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use AppBundle\Entity\Task; use Symfony\Component\HttpFoundation\Request; class DefaultController extends Controller { public function newAction(Request $request) { // create a task and give it some dummy data for this example $task = new Task(); $task->setTask('Write a blog post'); $task->setDueDate(new \DateTime('tomorrow')); $form = $this->createFormBuilder($task) ->add('task', 'text') ->add('dueDate', 'date') ->add('save', 'submit', array('label' => 'Create Task')) ->getForm(); return $this->render('Default/new.html.twig', array( 'form' => $form->createView(), )); } } </syntaxhighlight> === Form classes === The convention is to put form classes in `src/AppBundle/Form/Type/`. <syntaxhighlight lang="php"> // src/AppBundle/Form/Type/TaskType.php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class TaskType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('task') ->add('dueDate', null, array('widget' => 'single_text')) ->add('save', 'submit'); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Task', )); } public function getName() { return 'task'; } } </syntaxhighlight> `getName()` should return a unique identifier to be used by the controller. To use the form class in the controller: <syntaxhighlight lang="php" highlight="4,9"> // src/AppBundle/Controller/DefaultController.php // add this new use statement at the top of the class use AppBundle\Form\Type\TaskType; public function newAction() { $task = ...; $form = $this->createForm(new TaskType(), $task); // ... } </syntaxhighlight> === Services for forms === Once the form class is built, it can be set up as a service. <syntaxhighlight lang="yaml"> # src/AppBundle/Resources/config/services.yml services: acme_demo.form.type.task: class: AppBundle\Form\Type\TaskType tags: - { name: form.type, alias: task } </syntaxhighlight> To use the form service in a controller (note that the `use` statement isn't necessary now): <syntaxhighlight lang="php" highlight="8"> // src/AppBundle/Controller/DefaultController.php // ... public function newAction() { $task = ...; $form = $this->createForm('task', $task); // ... } </syntaxhighlight> Or to use the form service in another form class: <syntaxhighlight lang="php" highlight="11"> // src/AppBundle/Form/Type/ListType.php // ... class ListType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // ... $builder->add('someTask', 'task'); } } </syntaxhighlight> == Render a form == After passing a form "view" object to a Twig template, the form can be rendered with form helper functions:<ref>[http://symfony.com/doc/current/book/forms.html#rendering-the-form Rendering The Form], Symfony forms documentation</ref> <syntaxhighlight lang="twig"> {# app/Resources/views/Default/new.html.twig #} {{ form_start(form) }} {{ form_errors(form) }} {{ form_widget(form) }} {{ form_end(form) }} </syntaxhighlight> `form_end(form)` renders the form's end tag along with hidden fields, including CSRF protection. It also renders any fields that have not already been rendered. === Rendering form fields === * `form_row(form.property)` renders a form input along with a label and error messages specific to the form field. `form` is the name of the form variable, and `property` is the name of the property being rendered, e.g. `form.id`, `form.name`, etc. * The components wrapped up in `form_row()` can be rendered separately: ** `form_label(form.property)` renders just the label for the field. *** Override the label text with `form_label(form.property, 'Custom Label Text')` ** `form_errors(form.property)` renders errors for the field. ** `form_widget(form.property)` renders the form input. *** Set properties for the input with `form_widget(form.property, {`attr`: {'class': 'my-custom-class'}})` * Individual properties of the fields can be accessed with ** `form.entity.property.id` ** `form.entity.property.name` ** `form.entity.property.label` ** <span style="color:orange;">''^^ Actually I'm not 100% sure that's how it works. Try it out to confirm.''</span> === See also === * [[Customizing Symfony Form Templates]] * [[Inserting a Hidden Date Field in a Symfony Form]] == Handling form submissions == In the controller, the form object translates user data submitted with the form.<ref>[http://symfony.com/doc/current/book/forms.html#handling-form-submissions Handling Form Submissions], Symfony forms documentation</ref> <syntaxhighlight lang="php" highlight="12,14,16"> public function newAction(Request $request) { // just setup a fresh $task object (remove the dummy data) $task = new Task(); $form = $this->createFormBuilder($task) ->add('task', 'text') ->add('dueDate', 'date') ->add('save', 'submit', array('label' => 'Create Task')) ->getForm(); $form->handleRequest($request); if ($form->isValid()) { // perform some action, such as saving the task to the database return $this->redirect($this->generateUrl('task_success')); } // ... } </syntaxhighlight> # When the page is first loaded, the form is created and rendered. ## `handleRequest()` recognizes that the form was not submitted and does nothing. ## `isValid()` returns `false` if the form was not submitted. # When the form is submitted, `handleRequest()` translates the data ## `handleRequest()` updates the corresponding properties of the entity object (`$task` in this case) with the form data. ## `isValid()` returns `false` if the form data isn't valid. ### Execution skips that block where the data would be processed, and instead goes to the original view, which is rendered with the submitted form data and error messages. === Multiple submit buttons === Add the buttons to the form builder in the controller:<ref>[http://symfony.com/doc/current/book/forms.html#submitting-forms-with-multiple-buttons Submitting Forms With Multiple Buttons], Symfony forms documentation</ref> <syntaxhighlight lang="php" highlight="4-5"> $form = $this->createFormBuilder($task) ->add('task', 'text') ->add('dueDate', 'date') ->add('save', 'submit', array('label' => 'Create Task')) ->add('saveAndAdd', 'submit', array('label' => 'Save and Add')) ->getForm(); </syntaxhighlight> Test which button was clicked in the controller using the button's `isClicked()` method: <syntaxhighlight lang="php" highlight="4-6"> if ($form->isValid()) { // ... perform some action, such as saving the task to the database $nextAction = $form->get('saveAndAdd')->isClicked() ? 'task_new' : 'task_success'; return $this->redirect($this->generateUrl($nextAction)); } </syntaxhighlight> === Form validation === With Symfony, it isn't the form that is validated, rather it is the entity object that is tested to confirm that it contains valid data. This is does by defining a set of rules, or constraints, for the entity class.<ref>[http://symfony.com/doc/current/book/forms.html#form-validation Form Validation], Symfony forms documentation</ref> <syntaxhighlight lang="yaml"> # AppBundle/Resources/config/validation.yml AppBundle\Entity\Task: properties: task: - NotBlank: ~ dueDate: - NotBlank: ~ - Type: \DateTime </syntaxhighlight> The above configuration specifies that the `task` field cannot be empty and the `dueDate` field cannot be empty and must be a valid DateTime object. ==== Validation groups ==== Different groups can be defined to validate the underlying object, either in the controller: <syntaxhighlight lang="php"> $form = $this->createFormBuilder($users, array( 'validation_groups' => array('registration'), ))->add(...); </syntaxhighlight> Or in a form class: <syntaxhighlight lang="php"> use Symfony\Component\OptionsResolver\OptionsResolverInterface; public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'validation_groups' => array('registration'), )); } </syntaxhighlight> ==== Disabling validation ==== Set the `validation_groups` option to `false`: <syntaxhighlight lang="php"> public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'validation_groups' => false, )); } </syntaxhighlight> == Forms without classes == Example of how to set this up in a controller:<ref>[http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class Using a Form Without a Class], Symfony forms documentation</ref> <syntaxhighlight lang="php"> // make sure you've imported the Request namespace above the class use Symfony\Component\HttpFoundation\Request; // ... public function contactAction(Request $request) { $defaultData = array('message' => 'Type your message here'); $form = $this->createFormBuilder($defaultData) ->add('name', 'text') ->add('email', 'email') ->add('message', 'textarea') ->add('send', 'submit') ->getForm(); $form->handleRequest($request); if ($form->isValid()) { // data is an array with "name", "email", and "message" keys $data = $form->getData(); } // ... render the form } </syntaxhighlight> === See also === * [[Forms With Checkboxes For Each Entity in Symfony]] == See also == * [[Listings Filters Form With Symfony]] == Notes == <references />
Summary:
Please note that all contributions to Littledamien Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Littledamien Wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information