Skip to content

Commit

Permalink
[5.x] Refactor frontend formFailure to handle precognitive and fetch …
Browse files Browse the repository at this point in the history
…exceptions (#10376)
  • Loading branch information
ryanmitchell authored Jul 1, 2024
1 parent cfbe3eb commit dacb506
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/Http/Controllers/FormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,15 @@ private function validateContentType($request, $form)
* The steps for a failed form submission.
*
* @param array $params
* @param array $submission
* @param array $errors
* @param string $form
* @return Response|RedirectResponse
*/
private function formFailure($params, $errors, $form)
{
if (request()->ajax() || request()->wantsJson()) {
$request = request();

if ($request->ajax()) {
return response([
'errors' => (new MessageBag($errors))->all(),
'error' => collect($errors)->map(function ($errors, $field) {
Expand All @@ -116,6 +118,10 @@ private function formFailure($params, $errors, $form)
], 400);
}

if ($request->isPrecognitive() || $request->wantsJson()) {
throw ValidationException::withMessages($errors);
}

$redirect = Arr::get($params, '_error_redirect');

$response = $redirect ? redirect($redirect) : back();
Expand Down
45 changes: 45 additions & 0 deletions tests/Tags/Form/FormCreateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -932,4 +932,49 @@ public function it_removes_any_uploaded_assets_when_a_listener_throws_a_validati

Storage::disk('avatars')->assertMissing('avatar.jpg');
}

#[Test]
public function it_renders_exceptions_thrown_during_json_requests_as_standard_laravel_errors()
{
Event::listen(function (\Statamic\Events\FormSubmitted $event) {
throw ValidationException::withMessages(['some' => 'error']);
});

$response = $this
->postJson('/!/forms/contact', [
'name' => 'Name',
'email' => 'test@test.com',
'message' => 'This is a message',
]);

$json = $response->json();

$this->assertArrayHasKey('message', $json);
$this->assertArrayHasKey('errors', $json);
$this->assertSame($json['errors'], ['some' => ['error']]);
}

#[Test]
public function it_renders_exceptions_thrown_during_xml_http_requests_in_statamic_error_format()
{
Event::listen(function (\Statamic\Events\FormSubmitted $event) {
throw ValidationException::withMessages(['some' => 'error']);
});

$response = $this
->withHeaders([
'X-Requested-With' => 'XMLHttpRequest',
])
->postJson('/!/forms/contact', [
'name' => 'Name',
'email' => 'test@test.com',
'message' => 'This is a message',
]);

$json = $response->json();

$this->assertArrayHasKey('error', $json);
$this->assertArrayHasKey('errors', $json);
$this->assertSame($json['error'], ['some' => 'error']);
}
}

0 comments on commit dacb506

Please sign in to comment.