mirror of
https://github.com/codeigniter4/CodeIgniter4.git
synced 2025-02-20 11:44:28 +08:00
feat: add validation_show_error() in Form helper
This commit is contained in:
parent
7f2d5aefc8
commit
d8b337ec5f
@ -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
|
||||
|
@ -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
|
||||
{
|
||||
|
@ -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 ';
|
||||
|
Loading…
x
Reference in New Issue
Block a user