Skip to content
Advertisement

Codeigniter doesn’t let me update entry, because some fields must be unique

So what I’m trying to do:

  1. Pull User data from database, including email address, username etc.

  2. Edit it

  3. Save it

But I want to keep username and email unique. And for this I’m setting validation rules like this:

$this->form_validation->set_rules('firstname', 'First Name', 'required|min_length[2]|max_length[15]');
$this->form_validation->set_rules('lastname', 'Last Name', 'required|min_length[2]|max_length[15]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]|is_unique[users.username]');
$this->form_validation->set_rules('password1', 'Password', 'required|matches[password2]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'required');
$this->form_validation->set_rules('group', 'User Group', 'required');

And as you can see I have is_unique[users.username] and is_unique[users.email] rules. But it doesn’t let me update my entry using this rules.

So the question is, how can I update database entry, and keep those 2 fields unique(username and email)?

Advertisement

Answer

use the call back validation function

$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_check_user_email');

function check_user_email($email) {        
    if($this->input->post('id'))
        $id = $this->input->post('id');
    else
        $id = '';
    $result = $this->user_model->check_unique_user_email($id, $email);
    if($result == 0)
        $response = true;
    else {
        $this->form_validation->set_message('check_user_email', 'Email must be unique');
        $response = false;
    }
    return $response;
}

in model

    function check_unique_user_email($id = '', $email) {
        $this->db->where('email', $email);
        if($id) {
            $this->db->where_not_in('id', $id);
        }
        return $this->db->get('user')->num_rows();
    }

use same for the user name….

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement