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

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




Theme © iAndrew 2016 - Forum software by © MyBB