Skip to content

Commit

Permalink
feat: add validation_list_errors() in Form helper
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Aug 18, 2022
1 parent ea03027 commit 8c78b26
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
21 changes: 21 additions & 0 deletions system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* the LICENSE file that was distributed with this source code.
*/

use CodeIgniter\Validation\Exceptions\ValidationException;
use Config\App;
use Config\Services;

Expand Down Expand Up @@ -711,6 +712,26 @@ function validation_errors(): array
}
}

if (! function_exists('validation_list_errors')) {
/**
* Returns the rendered HTML of the validation errors.
*
* See Validation::listErrors()
*/
function validation_list_errors(string $template = 'list'): string
{
$config = config('Validation');
$view = Services::renderer();

if (! array_key_exists($template, $config->templates)) {
throw ValidationException::forInvalidTemplate($template);
}

return $view->setVar('errors', validation_errors())
->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 @@ -500,6 +500,8 @@ public function setRuleGroup(string $group)

/**
* Returns the rendered HTML of the errors as defined in $template.
*
* You can also use validation_list_errors() in Form helper.
*/
public function listErrors(string $template = 'list'): 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 @@ -943,6 +943,16 @@ public function testValidationErrorsFromValidation()
$this->assertSame(['id' => 'The ID field is required.'], validation_errors());
}

public function testValidationListErrors()
{
$validation = Services::validation();
$validation->setRule('id', 'ID', 'required')->run([]);

$html = validation_list_errors();

$this->assertStringContainsString('<li>The ID field is required.</li>', $html);
}

public function testFormParseFormAttributesTrue()
{
$expected = 'readonly ';
Expand Down

0 comments on commit 8c78b26

Please sign in to comment.