Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e25a637

Browse files
committed
[FrameworkBundle] Add AbstractController::handleForm() helper
1 parent 1a399ae commit e25a637

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php

+17-6
Original file line numberDiff line numberDiff line change
@@ -291,15 +291,26 @@ protected function stream(string $view, array $parameters = [], StreamedResponse
291291
}
292292

293293
/**
294-
* Renders a form.
294+
* Handles a form.
295295
*
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
298302
*/
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
300304
{
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()) {
303314
$response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
304315
}
305316

0 commit comments

Comments
 (0)