0

我正在尝试使用 codeigniter 停止数据库中的重复条目。当我插入数据时它工作正常,但是当我更新数据时它不起作用。如果我只更改描述而不是部门名称,它会给出已经存在的消息。

为此,我在控制器中使用以下代码:

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

4

2 回答 2

0

您必须编写验证代码。

方法一:验证回调

您的规则声明:

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

该方法在验证的同一控制器中:

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;
}

回调:您自己的验证函数

方法二:扩展 Form_validation 以添加新的验证规则

您的规则声明:

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

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

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();
    }

}

扩展原生库

*没有经过测试的代码

于 2013-11-11T12:46:02.917 回答
0

您可以在验证规则中使用回调函数。例如

$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

}
于 2013-11-11T12:51:50.827 回答