From 7ea834bcd1fba95b85870402fd56b248940c096b Mon Sep 17 00:00:00 2001 From: kenjis Date: Thu, 18 Aug 2022 15:42:26 +0900 Subject: [PATCH] feat: add validation_show_error() in Form helper --- system/Helpers/form_helper.php | 26 +++++++++++++++++++++++++ system/Validation/Validation.php | 2 ++ tests/system/Helpers/FormHelperTest.php | 10 ++++++++++ 3 files changed, 38 insertions(+) diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index fb74da239606..7a3d5370f6ce 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -732,6 +732,32 @@ function validation_list_errors(string $template = 'list'): string } } +if (! function_exists('validation_show_error')) { + /** + * Displays a single error in formatted HTML. + * + * See Validation::showError() + */ + function validation_show_error(string $field, string $template = 'single'): string + { + $config = config('Validation'); + $view = Services::renderer(); + + $errors = validation_errors(); + + if (! array_key_exists($field, $errors)) { + return ''; + } + + if (! array_key_exists($template, $config->templates)) { + throw ValidationException::forInvalidTemplate($template); + } + + return $view->setVar('error', $errors[$field]) + ->render($config->templates[$template]); + } +} + if (! function_exists('parse_form_attributes')) { /** * Parse the form attributes diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index cd580812904a..312048c0037a 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -516,6 +516,8 @@ public function listErrors(string $template = 'list'): string /** * Displays a single error in formatted HTML as defined in the $template view. + * + * You can also use validation_show_error() in Form helper. */ public function showError(string $field, string $template = 'single'): string { diff --git a/tests/system/Helpers/FormHelperTest.php b/tests/system/Helpers/FormHelperTest.php index db67d58b56e6..fdeda5534963 100644 --- a/tests/system/Helpers/FormHelperTest.php +++ b/tests/system/Helpers/FormHelperTest.php @@ -953,6 +953,16 @@ public function testValidationListErrors() $this->assertStringContainsString('
  • The ID field is required.
  • ', $html); } + public function testValidationShowError() + { + $validation = Services::validation(); + $validation->setRule('id', 'ID', 'required')->run([]); + + $html = validation_show_error('id'); + + $this->assertSame('The ID field is required.' . "\n", $html); + } + public function testFormParseFormAttributesTrue() { $expected = 'readonly ';