check uniqueness in codeigniter formvalidation when editing
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function __construct(){
parent::__construct();
}
function error_array(){
return $this->_error_array;
}
public function is_unique($str, $field) {
$field_ar = explode('.', $field);
$query = $this->CI->db->get_where($field_ar[0], array($field_ar[1] => $str), 1, 0);
if ($query->num_rows() === 0) {
return TRUE;
}
return FALSE;
}
function unique_check($str, $field)
{
list($field,$exclude)=explode(',', $field);
list($table, $field) = explode('.', $field);
if(!empty($exclude))
{
list($field_name, $post_field) = explode('.', $exclude);
$value= $this->CI->input->post($post_field);
$this->CI->db->where_not_in($field_name,$value);
}
if (isset($this->CI->db))
{
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
return $query->num_rows() === 0;
}
return FALSE;
}
}
?>
in controller
assume that you have to update coloum_id value in database and your text field name is field_id_name
$rules = array(
array(
'field' => 'field_id_name',
'label' => 'field id label',
'rules' => 'trim|required'
),
array(
'field' => 'field_name',
'label' => 'field label',
'rules' => 'trim|required|unique_check[table_name.coloumname,coloum_id.field_id_name]'
),
class MY_Form_validation extends CI_Form_validation {
function __construct(){
parent::__construct();
}
function error_array(){
return $this->_error_array;
}
public function is_unique($str, $field) {
$field_ar = explode('.', $field);
$query = $this->CI->db->get_where($field_ar[0], array($field_ar[1] => $str), 1, 0);
if ($query->num_rows() === 0) {
return TRUE;
}
return FALSE;
}
function unique_check($str, $field)
{
list($field,$exclude)=explode(',', $field);
list($table, $field) = explode('.', $field);
if(!empty($exclude))
{
list($field_name, $post_field) = explode('.', $exclude);
$value= $this->CI->input->post($post_field);
$this->CI->db->where_not_in($field_name,$value);
}
if (isset($this->CI->db))
{
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
return $query->num_rows() === 0;
}
return FALSE;
}
}
?>
in controller
assume that you have to update coloum_id value in database and your text field name is field_id_name
$rules = array(
array(
'field' => 'field_id_name',
'label' => 'field id label',
'rules' => 'trim|required'
),
array(
'field' => 'field_name',
'label' => 'field label',
'rules' => 'trim|required|unique_check[table_name.coloumname,coloum_id.field_id_name]'
),
Comments
Post a Comment