How to Use the submit() Function to Handle Form Submissions
How to Use the submit() Function to Handle Form Submissions¶
With the handleRequest()
method, it is really easy to handle form
submissions:
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('AppBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
Tip
To see more about this method, read Handling Form Submissions.
Calling Form::submit() manually¶
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()
:
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('AppBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
Tip
Forms consisting of nested fields expect an array in
submit()
. You can also submit
individual fields by calling submit()
directly on the field:
$form->get('firstName')->submit('Fabien');
Tip
When submitting a form via a “PATCH” request, you may want to update only a few
submitted fields. To achieve this, you may pass an optional second boolean
parameter to submit()
. Passing false
will remove any missing fields
within the form object. Otherwise, the mising fields will be set to null
.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.