feat: add validation_show_error() in Form helper

This commit is contained in:
kenjis 2022-08-18 15:42:26 +09:00
parent 7f2d5aefc8
commit d8b337ec5f
No known key found for this signature in database
GPG Key ID: BD254878922AF198
3 changed files with 38 additions and 0 deletions

View File

@ -732,6 +732,32 @@ if (! function_exists('validation_list_errors')) {
}
}
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

View File

@ -516,6 +516,8 @@ class Validation implements ValidationInterface
/**
* 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
{

View File

@ -953,6 +953,16 @@ final class FormHelperTest extends CIUnitTestCase
$this->assertStringContainsString('<li>The ID field is required.</li>', $html);
}
public function testValidationShowError()
{
$validation = Services::validation();
$validation->setRule('id', 'ID', 'required')->run([]);
$html = validation_show_error('id');
$this->assertSame('<span class="help-block">The ID field is required.</span>' . "\n", $html);
}
public function testFormParseFormAttributesTrue()
{
$expected = 'readonly ';