shield
shield copied to clipboard
fix: redirect()->withInput() or withErrors() causes ValidationException
Fixes https://github.com/codeigniter4/shield/discussions/381
redirect()->withInput() or withErrors() saves validation errors in the Session.
And the check of the validation errors in Model (checkQueryReturn()),
$this->validation->getErrors() returns the errors in the Session.
How to Test
--- a/app/Config/Filters.php
+++ b/app/Config/Filters.php
@@ -36,6 +36,7 @@ class Filters extends BaseConfig
// 'honeypot',
// 'csrf',
// 'invalidchars',
+ 'session' => ['except' => 'login*'],
],
'after' => [
'toolbar',
--- a/app/Controllers/Home.php
+++ b/app/Controllers/Home.php
@@ -2,10 +2,22 @@
namespace App\Controllers;
+use Config\Services;
+
class Home extends BaseController
{
public function index()
{
- return view('welcome_message');
+ $this->validation = Services::validation();
+
+ $this->validation->setRules([
+ 'email' => 'required|valid_email|unique_email[{user_id}]',
+ ]);
+
+ if (! $this->validation->withRequest($this->request)->run()) {
+ return redirect()
+ ->to('logout')
+ ->withInput();
+ }
}
}
@kenjis, I think we should merge this PR. The number of people involved in PR seems to be high. according to what you did recently for hotfix CI, we can proceed to write the test after the merge.
+1 for merge now, It's breaking app at all.
To merge, we need reviews.
@kenjis For me this PR solved validation in forms.
I don't like the production use of reflection. It's hard to trace this back in mobile, but couldn't this be solved by handling our validations from a clean instance?
// Validate the registration
if (! single_service('validation')->setRules($this->registrationRules)->run($event)) {
...
couldn't this be solved by handling our validations from a clean instance?
No, because the session data ($_SESSION) is global.
See https://github.com/codeigniter4/CodeIgniter4/pull/6381 It helps your understanding.
That helps! Okay I am on board with the Reflection solution. It's a hack but we have a fix in framework at least. Maybe add a note that if the minimum CI4 version is ever increased past 4.2.4 then it can be refactored. Or alternatively, check the actual version and have Reflection be the fallback solution.