Skip to content

Commit

Permalink
feat: add validation_show_error() in Form helper
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Aug 18, 2022
1 parent 4157c47 commit 7ea834b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
26 changes: 26 additions & 0 deletions system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions system/Validation/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
10 changes: 10 additions & 0 deletions tests/system/Helpers/FormHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,16 @@ public function testValidationListErrors()
$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 ';
Expand Down

0 comments on commit 7ea834b

Please sign in to comment.