Question

I'm working on a login-functionality for a user in Codeigniter.

This is part of my User-controller:

public function login() {
    $name = $this->input->post('username');
    $pass = $this->input->post('pass');

    $this->form_validation->set_rules('username', 'Användarnamn', 'required');
    $this->form_validation->set_rules('pass', 'Lösenord', 'required');

    //Username or password not given
    if ($this->form_validation->run() == false) {
            $succesful = false;                        
    }
    else {
            //Form itself validates (Username and password is given)
            //Check if username and password matches against some user in the database
            $um = new Usermodel();
            $um->setUsername($name);
            $um->setPassword($pass);

            //True if account exists or false if it does not
            $succesful = $um->accountExists(); 
    }

    $data = array();
    $succesful = false; //TEMP
    if ($succesful === false) {
            $data['error'] = 'groovy';
            $this->form_validation->set_message('username', 'groovy' );                        
    }

    //Show template
    $data['loginform'] = $this->loginform();
    $data['registerform'] = $this->registerform();
    $this->load->view('home', $data);
}

Snippet from my view (home) looks like:

<?php 
echo validation_errors(); //Show errors if they occur on submit
if (isset($error)) {
    echo $error;
}
if (isset($loginform)) {
    echo $loginform;
}
if (isset($registerform)) {
    echo $registerform;   
}                
?>

When a user hits submit on the loginform, the login() function is called. If login fails with match of user from database, then the word groovy is echoed out.

Is there a way to do acheive this WITHOUT using $data['error'] = 'groovy' ?

What I want to do is to replace:

echo validation_errors(); //Show errors if they occur on submit
if (isset($error)) {
    echo $error;
}

with

echo validation_errors(); //Show errors if they occur on submit

in my view (where validation_errors() should return groovy)

This just specifies value when input username is incorrectly (based on the rules) if I understand correctly.

$this->form_validation->set_message('username', 'groovy' ); 
Was it helpful?

Solution

Extend the Form Validation class and add a custom function to add messages to the error array (which is where validation_errors() gets its messages);

libraries/MY_Form_validation.php

class MY_Form_validation extends CI_Form_validation
{
    public function add_error($field, $message)
    {
        if ( ! isset($this->_error_array[$field]))
        {
            $this->_error_array[$field] = $message;
        }

        return;
    }
}

controller:

$succesful = false; //TEMP
if ($succesful === false) {
        $this->form_validation->add_error('username', 'Username is groovy!');                        
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top