Symfony Forms Cookbook: Difference between revisions

From Littledamien Wiki
Jump to navigation Jump to search
(Created page with "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>[ht...")
 
No edit summary
Line 44: Line 44:
{{ form_end(form) }}
{{ form_end(form) }}
</syntaxhighlight>
</syntaxhighlight>
== 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.
== Notes ==
<references />

Revision as of 00:35, 5 February 2015

Basic form building

Build a form object and render it in a template from within a controller:[1]

// 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(),
        ));
    }
}

Render a form

After passing a form "view" object to a Twig template, the form can be rendered with form helper functions:[2]

{# app/Resources/views/Default/new.html.twig #}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

Handling form submissions

In the controller, the form object translates user data submitted with the form.[3]

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'));
    }

    // ...
}
  1. When the page is first loaded, the form is created and rendered.
    1. handleRequest() recognizes that the form was not submitted and does nothing.
    2. isValid() returns false if the form was not submitted.
  2. When the form is submitted, handleRequest() translates the data
    1. handleRequest() updates the corresponding properties of the entity object ($task in this case) with the form data.
    2. isValid() returns false if the form data isn't valid.
      1. 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.

Notes

  1. Building The Form, Symfony forms documentation
  2. Rendering The Form, Symfony forms documentation
  3. Handling Form Submissions, Symfony forms documentation