Callback function of codeigniter which checks whether the value already exists in particular columnĀ of table or not.
This function work on add and edit both cases,it return false if value exists and return true if value not exists.
following is the function that you need to put in your controller file:
public function check_exist($string,$token){ if(!empty($string)){ $token=explode("-",$token); $column=$token[1]; if($token[0]=="add") { $where = array( $column => $string ); } if($token[0]=="edit") { $where = array( $column => $string, 'id!=' => $token[2] ); } $this->db->select('id'); $this->db->from('table_name'); $this->db->where($where); $num_results = $this->db->count_all_results(); if($num_results>0){ $this->form_validation->set_message('check_exist', 'The %s value is already exists.'); return false; }else{ return true; } } }
Note: change the table name in function and in edit case you can change the primary key!= with your table’s key name.
Now time to using this callback function for adding and editing forms.We need to pass the callback function in validation rules.
For the time of adding you can pass the rule in your add action like as:
array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[add-cat_name]' ), or $config = array ( array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[add-cat_name]' ), array( 'field' => 'slug', 'label' => 'Category Slug', 'rules' => 'trim|required|callback_check_exist[add-slug]' ), array( 'field' => 'description', 'label' => 'Category Description', 'rules' => 'trim|required' ), array( 'field' => 'parent_id', 'label' => 'Parent Category', 'rules' => 'trim' ), ); $this->form_validation->set_rules($config);
and in your edit action you can use the rule as following:
array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[edit-cat_name-'.$cat_id.']' ), OR $config = array ( array( 'field' => 'cat_title', 'label' => 'Category Title', 'rules' => 'trim|required|callback_check_exist[edit-cat_name-'.$cat_id.']' ), array( 'field' => 'slug', 'label' => 'Category Slug', 'rules' => 'trim|required|callback_check_exist[edit-slug-'.$cat_id.']' ), array( 'field' => 'description', 'label' => 'Category Description', 'rules' => 'trim|required' ), array( 'field' => 'parent_id', 'label' => 'Parent Category', 'rules' => 'trim' ), ); $this->form_validation->set_rules($config);
Thanks for reading full article , Now use it in your project and if you face any trouble then comment here.