Is_unique in codeigniter for editing function

I have a requirement where I can validate for a unique value in a new add function like

$this->form_validation->set_rules('email','Email','required|valid_email||is_unique[users.Email]');

      

its works, but in edit function it doesn't work. I wrote a callback function to validate unique email. this is the code i wrote in the edit function

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

function check_username($email)
    { 
        $return_value = $this->user_model->check_email($email);
        if ($return_value)
        {
            $this->form_validation->set_message('email_check', 'Sorry, This username is already used by another user please select another one');
            return FALSE;
        }
        else
        {
        return TRUE;
        }
    }

      

and user_model

function check_mail($email)
    { 
        $sql = "SELECT users.Email
                FROM users
                WHERE 
                $email = users.Email
                ";

        $result = $this->db->query($sql)->result_array();
        return $result;

    }

      

im failed to validate unique email

+5


source to share


8 answers


Try using this code in your controller (view)



    $original_value = $this->db->query("SELECT EMAIL FROM users WHERE id = ".$id)->row()->EMAIL ;
    if($this->input->post('username') != $original_value) {
       $is_unique =  '|is_unique[users.EMAIL]';
    } else {
       $is_unique =  '';
    }
$this->form_validation->set_rules('username', 'User Name', 'required|min_length[3]|max_length[30]|trim|xss_clean'.$is_unique);

      

+9


source


Simple solution inspired by is_unique from CodeIgniter.

Warning: Works only if the row id in the database is the typical "id". Although this code might fit easily.

Change is_unique to edit_unique and concatenate the id of the line you are editing, for example:

$this->form_validation->set_rules('email','Email','required|valid_email|edit_unique[users.Email.'.$id.']');

      

Then go to application / libraries folder and create MY_Form_validation.php with this code:



<?php

class MY_Form_validation extends CI_Form_validation{

    public function edit_unique($str, $field)
    {
        sscanf($field, '%[^.].%[^.].%[^.]', $table, $field, $id);
        return isset($this->CI->db)
            ? ($this->CI->db->limit(1)->get_where($table, array($field => $str, 'id !=' => $id))->num_rows() === 0)
            : FALSE;
    }

}

      

Then edit this file: application / system / language / english / form_validation_lang.php

And add this code to the end of the file:

$lang['form_validation_edit_unique']= 'The {field} field must contain a unique value.';

      

: D

+2


source


<?php

/* Create MY_Form_validation.php  in ci_root/application/libraries */

class MY_Form_validation extends CI_Form_validation {

public function is_unique($str, $field) {

    if (substr_count($field, '.') == 3) {
        list($table, $field, $id_field, $id_val) = explode('.', $field);
        $query = $this->CI->db->limit(1)->where($field, $str)->where($id_field . ' != ', $id_val)->get($table);
    } else {
        list($table, $field) = explode('.', $field);
        $query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
    }

    return $query->num_rows() === 0;
}

}
?>



<?php

/* implementation */

function update() {

$user_id = $this->input->post("user_id");
$rules = array(array(
        'field' => 'email',
        'label' => 'Email',
        'rules' => 'required|valid_email|is_unique[users.Email.id.' . $user_id . ']'));

$this->form_validation->set_rules($rules);
}

      

+1


source


Suppose the system prompts you to update your username in the app, and then:

File -> config / form_validation.php

$config = array(
    "add_user" => array(
        array('field' => 'name','label' => 'name','rules' =>'required','errors' => array(
            'required' => '%s is required.' 
        )),
        array('field' => 'username','label' => 'username','rules' =>'required|is_unique[tbl_users.username]','errors' => array(
            'required' => '%s is required.',
            'is_unique' => 'Sorry, that %s value is already being used.', 
        )),
        array('field' => 'password','label' => 'password','rules' =>'required','errors' => array(
            'required' => '%s is required.' 
        )),
    ),
    "update_user" => array(
        array('field' => 'name','label' => 'name','rules' =>'required','errors' => array(
            'required' => '%s is required.' 
        )),
        array('field' => 'username','label' => 'username','rules' =>'required|callback_unique_username','errors' => array(
            'required' => '%s is required.' 
            'unique_username' => 'Sorry, that %s value is already being used.' 
        )),
        array('field' => 'password','label' => 'password','rules' =>'required','errors' => array(
            'required' => '%s is required.' 
        )),
    )
)

      

File -> controller / Users.php

    public function unique_username($username){
        /* 
        * At the time of update you will be needing the user_id 
        * of particular user whose profile you want to update
        * we have placed user_id as hidden field in user update view 
        * form like 
        * <input type="hidden" value="{user_id here}" name="user_id">  
        */ 
        $this->db->where_not_in('user_id',$this->input->post('user_id'));
        $this->db->where('username',$username);
        if($this->db->count_all_results('tbl_users') > 0){
            return false;
        }else{
            return true;
        }
    }

      

+1


source


 $original_value = $this->db->query("select role_name from user_roles where iduser_roles = ".$iduser_roles)->row()->role_name ;
        if($this->input->post('role_name') != $original_value) {
            $is_unique =  '|is_unique[user_roles.role_name]';
        } else {
            $is_unique =  '';
        }

        $this->form_validation->set_rules('role_name', 'Role Name', 'trim|required|xss_clean'.$is_unique);

      

+1


source


Improve the "DrPollit0" solution that only supports "id" as the column name. This solution allows you to declare the column name as columnID

Create a custom validation class at application \ library \ MY_Form_validation.php

class MY_Form_validation extends CI_Form_validation
{
    public function __construct($rules = array())
    {
        $this->CI =& get_instance();
        parent::__construct($rules);
    }

    public function edit_unique($str, $field)
    {
        sscanf($field, '%[^.].%[^.].%[^.].%[^.]', $table, $field, $columnIdName, $id);
        return isset($this->CI->db)
            ? ($this->CI->db->limit(1)->get_where($table, array($field => $str, $columnIdName .'!=' => $id))->num_rows() === 0)
            : FALSE;
    }
}

      

Add this to system \ language \ english \ form_validation_lang.php

$lang['form_validation_edit_unique']= 'The supplied value is already taken.';

      

For use in your controller

$id = $this->uri->segment(3);
'rules' => 'trim|required|max_length[50]|edit_unique[mytable.mycolumn.columnID.'.$id.']'

      

+1


source


How is this more flexible:

public function edit_unique($str, $field)
    {
        sscanf($field, '%[^.].%[^.].%[^.]', $table, $field, $value);
        return isset($this->CI->db)
            ? ($this->CI->db->limit(1)->get_where($table, array(''.$field.' !=' => $value))->num_rows() === 0)
            : FALSE;
    }

      

0


source


Remove double || and place the single | just before is_unique and the name of your function check_username should be the name you provided immediately after the callback _ means that in your case it should be check_email .

0


source







All Articles