@@ -291,15 +291,26 @@ protected function stream(string $view, array $parameters = [], StreamedResponse
291
291
}
292
292
293
293
/**
294
- * Renders a form.
294
+ * Handles a form.
295
295
*
296
- * The FormView instance is passed to the template in a variable named "form".
297
- * If the form is invalid, a 422 status code is returned.
296
+ * * if the form is not submitted, $render is called
297
+ * * if the form is submitted but invalid, $render is called and a 422 HTTP status code is set if the current status hasn't been customized
298
+ * * if the form is submitted and valid, $onSuccess is called, usually this method saves the data and returns a 303 HTTP redirection
299
+ *
300
+ * @param callable(FormInterface): Response $onSuccess
301
+ * @param callable(FormInterface): Response $render
298
302
*/
299
- public function renderForm ( string $ view , FormInterface $ form , array $ parameters = [], Response $ response = null ): Response
303
+ public function handleForm ( Request $ request , FormInterface $ form , callable $ onSuccess , callable $ render ): Response
300
304
{
301
- $ response = $ this ->render ($ view , ['form ' => $ form ->createView ()] + $ parameters , $ response );
302
- if ($ form ->isSubmitted () && !$ form ->isValid ()) {
305
+ $ form ->handleRequest ($ request );
306
+
307
+ $ submitted = $ form ->isSubmitted ();
308
+ if ($ submitted && $ form ->isValid ()) {
309
+ return $ onSuccess ($ form );
310
+ }
311
+
312
+ $ response = $ render ($ form );
313
+ if ($ submitted && 200 === $ response ->getStatusCode ()) {
303
314
$ response ->setStatusCode (Response::HTTP_UNPROCESSABLE_ENTITY );
304
315
}
305
316
0 commit comments