Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_unique in codeigniter for edit function

i have requirement , where i m able to do validation for unique value in new add function like

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

its working but in edit function its not working..i have written callback function to check unique email. this is code i have written in 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;

    }

i m not able to validate the unique email

like image 634
webpic Avatar asked Dec 23 '14 13:12

webpic


2 Answers

Try this code in your controller (edit 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);
like image 186
Arun Avatar answered Sep 30 '22 14:09

Arun


Simple solution, inspired by is_unique code from CodeIgniter.

Warning: Only works if the identifier of the row in the database is the typical "id". Although, this code can be suited easily.

Change is_unique to edit_unique, and concatenate the id of the row that you are editing, like this:

$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 at the end of the file:

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

:D

like image 21
DrPollit0 Avatar answered Sep 30 '22 12:09

DrPollit0