Skip to content

Commit

Permalink
feat: add validation_errors() in Form helper
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Aug 17, 2022
1 parent 282789b commit d92376b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
31 changes: 31 additions & 0 deletions system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -680,12 +680,43 @@ function set_radio(string $field, string $value = '', bool $default = false): st
}
}

if (! function_exists('validation_errors')) {
/**
* Returns the validation errors that are stored in the session.
* To use this, you need to use `withInput()` for `redirect()`.
*
* The returned array should be in the following format:
* [
* 'field1' => 'error message',
* 'field2' => 'error message',
* ]
*
* @return array<string, string>
*/
function validation_errors(): array
{
session();

$errors = [];

// Check the session to see if any were
// passed along from a redirect withErrors() request.
if (isset($_SESSION['_ci_validation_errors']) && (ENVIRONMENT === 'testing' || ! is_cli())) {
$errors = unserialize($_SESSION['_ci_validation_errors']);
}

return $errors;
}
}

if (! function_exists('parse_form_attributes')) {
/**
* Parse the form attributes
*
* Helper function used by some of the form helpers
*
* @internal
*
* @param array|string $attributes List of attributes
* @param array $default Default values
*/
Expand Down
9 changes: 9 additions & 0 deletions tests/system/Helpers/FormHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,15 @@ public function testSetRadioDefault()
$this->assertSame('', set_radio('code', 'beta', false));
}

public function testValidationErrors()
{
$_SESSION = ['_ci_validation_errors' => 'a:1:{s:3:"foo";s:3:"bar";}'];

$this->assertSame(['foo' => 'bar'], validation_errors());

$_SESSION = [];
}

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

0 comments on commit d92376b

Please sign in to comment.