How to Use the submit() Function to Handle Form Submissions

How to Use the submit() Function to Handle Form Submissions

The recommended way of processing Symfony forms is to use the [handleRequest()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormInterface.php "Symfony\Component\Form\FormInterface::handleRequest()") method to detect when the form has been submitted. However, you can also use the [submit()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormInterface.php "Symfony\Component\Form\FormInterface::submit()") method to have better control over when exactly your form is submitted and what data is passed to it:

  1. use Symfony\Component\HttpFoundation\Request;
  2. use Symfony\Component\HttpFoundation\Response;
  3. // ...
  4. public function new(Request $request): Response
  5. {
  6. $task = new Task();
  7. $form = $this->createForm(TaskType::class, $task);
  8. if ($request->isMethod('POST')) {
  9. $form->submit($request->request->get($form->getName()));
  10. if ($form->isSubmitted() && $form->isValid()) {
  11. // perform some action...
  12. return $this->redirectToRoute('task_success');
  13. }
  14. }
  15. return $this->render('task/new.html.twig', [
  16. 'form' => $form->createView(),
  17. ]);
  18. }

Tip

Forms consisting of nested fields expect an array in [submit()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormInterface.php "Symfony\Component\Form\FormInterface::submit()"). You can also submit individual fields by calling [submit()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormInterface.php "Symfony\Component\Form\FormInterface::submit()") directly on the field:

  1. $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 argument to submit(). Passing false will remove any missing fields within the form object. Otherwise, the missing fields will be set to null.

Caution

When the second parameter $clearMissing is false, like with the “PATCH” method, the validation will only apply to the submitted fields. If you need to validate all the underlying data, add the required fields manually so that they are validated:

  1. // 'email' and 'username' are added manually to force their validation
  2. $form->submit(array_merge(['email' => null, 'username' => null], $request->request->all()), false);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.