CodeIgniter Forums
Codeigniter 4 form validation example, please. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: Codeigniter 4 form validation example, please. (/showthread.php?tid=76784)



Codeigniter 4 form validation example, please. - JLDR - 06-19-2020

Hello.
I'm loosing my head now with something I cannot achieve.

Imagine a view with a simple form.
A controller with 2 methods: one to echo the view. The other to process the form after submission.

Controller (home):
PHP Code:
public function index(){        
    return 
view('form');
}

public function 
submission(){
    
$result $this->validate([
        
'username' => 'required',
        
'password' => 'required'
    
]);

    if(!
$result){
        return 
redirect()->back()->withInput();
    } else {
        echo 
'Submission OK!';
    }


View (form)
PHP Code:
<?= $this->validator->listErrors() ?>


    <?= form_open('home/submission')?>

    <div>        
        <input type="text" name="username" value="<?= old('username'?>">
    </div>
    <div>        
        <input type="text" name="password" value="<?= old('password'?>">
    </div>
    <div>
        <input type="submit" value="Login">
    </div>
    </form> 

Question: How can I redirect to back, with input data AND with the validation errors so I can display them in the form view?


RE: Codeigniter 4 form validation example, please. - JLDR - 06-20-2020

OK, guys. Just to notice that I've found the solution. Well, I've made my study and get this. Don't know if it is the best one, but here it goes:

Controller (home):
PHP Code:
public function index()
{
    
$data = [];
    if(
session()->has('errors')){
        
$data['error'] = session('error');
    }
    return 
view('form'$data);
}

public function 
afterPost()
{
    if (
$this->request->getMethod() !== 'post') {
        return 
redirect()->to(site_url('home/index'));
    }

    
// validation
    
$val $this->validate([
        
'username' => 'required',
        
'password' => 'required'
    
]);
    if (!
$val) {
        return 
redirect()->to(site_url('home/index'))->withInput()->with('error'$this->validator);
    } else {
        echo 
'Form is OK!';
    }




View (form)

PHP Code:
<?php if (isset($error)) : ?>
        <?= $error->listErrors() ?>
<?php 
endif; ?>


<?= form_open('home/afterpost'?>

    <div>
        <input type="text" name="username" value="<?= old('username'?>">
    </div>
    <div>
        <input type="password" name="password" value="<?= old('password'?>">
    </div>
    <div>
        <input type="submit" value="Login">
    </div>
</form>