Skip to content

Commit 927dc43

Browse files
committed
feat: add validation_errors() in Form helper
1 parent 57f699b commit 927dc43

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

system/Helpers/form_helper.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,12 +680,43 @@ function set_radio(string $field, string $value = '', bool $default = false): st
680680
}
681681
}
682682

683+
if (! function_exists('validation_errors')) {
684+
/**
685+
* Returns the validation errors that are stored in the session.
686+
* To use this, you need to use `withInput()` for `redirect()`.
687+
*
688+
* The returned array should be in the following format:
689+
* [
690+
* 'field1' => 'error message',
691+
* 'field2' => 'error message',
692+
* ]
693+
*
694+
* @return array<string, string>
695+
*/
696+
function validation_errors(): array
697+
{
698+
session();
699+
700+
$errors = [];
701+
702+
// Check the session to see if any were
703+
// passed along from a redirect withErrors() request.
704+
if (isset($_SESSION['_ci_validation_errors']) && (ENVIRONMENT === 'testing' || ! is_cli())) {
705+
$errors = unserialize($_SESSION['_ci_validation_errors']);
706+
}
707+
708+
return $errors;
709+
}
710+
}
711+
683712
if (! function_exists('parse_form_attributes')) {
684713
/**
685714
* Parse the form attributes
686715
*
687716
* Helper function used by some of the form helpers
688717
*
718+
* @internal
719+
*
689720
* @param array|string $attributes List of attributes
690721
* @param array $default Default values
691722
*/

tests/system/Helpers/FormHelperTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,15 @@ public function testSetRadioDefault()
926926
$this->assertSame('', set_radio('code', 'beta', false));
927927
}
928928

929+
public function testValidationErrors()
930+
{
931+
$_SESSION = ['_ci_validation_errors' => 'a:1:{s:3:"foo";s:3:"bar";}'];
932+
933+
$this->assertSame(['foo' => 'bar'], validation_errors());
934+
935+
$_SESSION = [];
936+
}
937+
929938
public function testFormParseFormAttributesTrue()
930939
{
931940
$expected = 'readonly ';

0 commit comments

Comments
 (0)