Welcome Guest, Not a member yet? Register   Sign In
Codeigniter 4 form validation example, please.
#2

(This post was last modified: 06-20-2020, 01:52 AM by JLDR.)

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> 
Reply


Messages In This Thread
RE: Codeigniter 4 form validation example, please. - by JLDR - 06-20-2020, 01:49 AM



Theme © iAndrew 2016 - Forum software by © MyBB