How to Use the submit() Function to Handle Form Submissions
How to Use the submit() Function to Handle Form Submissions¶
New in version 2.3: The handleRequest()
method was introduced in Symfony 2.3.
With the handleRequest()
method, it is really easy to handle form
submissions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
|
Tip
To see more about this method, read Handling Form Submissions.
Calling Form::submit() manually¶
New in version 2.3: Before Symfony 2.3, the submit()
method was known as bind()
.
In some cases, you want better control over when exactly your form is submitted
and what data is passed to it. Instead of using the
handleRequest()
method, pass the submitted data directly to
submit()
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
}
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
|
Passing a Request to Form::submit() (Deprecated)¶
New in version 2.3: Before Symfony 2.3, the submit
method was known as bind
.
Before Symfony 2.3, the submit()
method accepted a Request
object as
a convenient shortcut to the previous example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
if ($request->isMethod('POST')) {
$form->submit($request);
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
}
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
|
Passing the Request
directly to
submit()
still works, but is
deprecated and will be removed in Symfony 3.0. You should use the method
handleRequest()
instead.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.