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

跟風遠走 提交于 2019-12-24 04:03:12

问题


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)?


回答1:


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



来源:https://stackoverflow.com/questions/30481955/codeigniter-doesnt-let-me-update-entry-because-some-fields-must-be-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!