0
votes

I am trying to stop duplicate entry in database using codeigniter. It works fine when I insert data but when I update the data it is not working.. If I am change only description not departmentname it give already exist message.

For that I am using bellow code in my controller:

$this->form_validation->set_rules('departmentname', 'Departmentname', 'trim|required|xss_clean|is_unique[department_master.departmentname]');

2
try to write custom unique validation for updaterajesh kakawat

2 Answers

0
votes

You have to write your validation code.

Method 1: Validation Callback

Your rule declaration:

$this->form_validation->set_rules('field', 'label', 'callback__is_unique2');

The method, in the same controller that the validation:

public function _is_unique2($input) {
    $exclude_id = $this->input->post('id');

    if( $this->db->where('departmentname', $input)->where('id !=', $exclude_id)
        ->limit(1)->get('department_master')->num_rows())
    {
        $this->form_validation->set_message('_is_unique2', 'name exists');
        return FALSE;
    }

    return TRUE;
}

Callbacks: Your own Validation Functions

Method 2: Extend Form_validation to add a new validation rule

Your rule declaration:

$exlclude_id = $this->input->post('id');

$this->form_validation->set_rules('field', 'label',
 'is_unique2[department_master.departmentname.id_field.'.$exclude_id.']');

The extend of Form_validation,

//Libraries/MY_Form_validation.php

class MY_Form_validation extends CI_Form_validation {

    public function __construct() {
        parent::__construct();
    }

    public function is_unique2($str, $field)
    {
        list($table, $field, $exclude_field, $exclude_value)=explode('.', $field);

        return (bool) $this->CI->db
            ->where($field, $str)
            ->where($exclude_field.' !=', $exclude_value)
            ->limit(1)
            ->get($table)->num_rows();
    }

}

Extending Native Libraries

*No tested code

0
votes

You can use callback function in validation rules. For example

$this->form_validation->set_rules('departmentname', 'Departmentname', 'trim|required|xss_clean|is_unique[department_master.departmentname]|**callback_is_unique_department**');
Callback function take first argument in a function is field value itself.

public function is_unique_department($dep_name)
{
   // select query which find same department value exists or not if exists then write

    $this->form_validation->set_message('is_unique_department', 'This Department Name is already exists.');
     return false;

   else write return false

}