diff --git a/Event/RequestListener.php b/Event/RequestListener.php
index 7701c4b6..af06c5bf 100644
--- a/Event/RequestListener.php
+++ b/Event/RequestListener.php
@@ -17,7 +17,9 @@
use Sulu\Bundle\FormBundle\Form\HandlerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
+use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
+use Symfony\Component\HttpKernel\Event\ResponseEvent;
class RequestListener
{
@@ -41,6 +43,14 @@ class RequestListener
*/
protected $eventDispatcher;
+ /**
+ * Flag set to true when an invalid form is submitted,
+ * so we can set the http return code to 422.
+ *
+ * @var bool
+ */
+ protected $invalidSubmittedForm = false;
+
/**
* RequestListener constructor.
*/
@@ -73,10 +83,16 @@ public function onKernelRequest(RequestEvent $event): void
try {
$form = $this->formBuilder->buildByRequest($request);
- if (!$form || !$form->isSubmitted() || !$form->isValid()) {
+ if (!$form || !$form->isSubmitted()) {
// do nothing when no form was found or not valid
return;
}
+
+ if ($form && $form->isSubmitted() && !$form->isValid()) {
+ $this->invalidSubmittedForm = true;
+
+ return;
+ }
} catch (\Exception $e) {
// Catch all exception on build form by request
return;
@@ -96,4 +112,19 @@ public function onKernelRequest(RequestEvent $event): void
$event->setResponse($response);
}
}
+
+ public function onKernelResponse(ResponseEvent $event): void
+ {
+ if (\method_exists($event, 'isMainRequest') ? !$event->isMainRequest() : !$event->isMasterRequest()) {
+ // do nothing if it's not the master request
+ return;
+ }
+
+ if ($this->invalidSubmittedForm) {
+ $response = $event->getResponse() ?? new Response();
+ $response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
+
+ $event->setResponse($response);
+ }
+ }
}
diff --git a/Resources/config/services.xml b/Resources/config/services.xml
index 751051a4..885566b4 100644
--- a/Resources/config/services.xml
+++ b/Resources/config/services.xml
@@ -104,6 +104,7 @@
+