Deal All,
I have a controller which is extending the CI_Controller like this;
class MY_Controller extends CI_Controller
{
function check_unique($table, $field, $message_label, $value, $except_id){
$query = "SELECT * FROM $table WHERE $field = $value AND id != $except_id LIMIT 1";
if(count($this->db->query($query)->row_array()) == 0 ){
return TRUE;
}else{
$this->form_validation->set_message($field, "The field '" . $message_label . "' is not available. Please try a different value.");
return FALSE;
}
}
}
In my Client class -> edit function, that is...,
class Client extends MY_Controller
{
function edit($id){
$this->form_validation->set_rules("name", "Name", "required|max_length[50]");
}
}
...I want to check if name is being duplicated while update. Is there a way I can call the "check_unique" function from the controller in the validation rules?
You can use Form validation libraries callback feature to call your custom validation functions.
As your custom validation method is in MY_Controller
and you are inheriting it in your Client
class it will work fine as following.
function edit($id){
$this->form_validation->set_rules("name", "Name", "required|max_length[50]|callback_check_unique");
}
Remember you need call your function using
callback_
prefix.
In the Callback function, you can pass arguments as well. By default, CI will pass string parameter as an argument to your callback function. So you may need to modify your custom function little bit