用edit_unique编辑表单(重新填充)


Codeigniter - edit form (repopulating) with edit_unique

似乎edit_unique函数,在这里描述- 在更新记录时验证CodeIgniter中的唯一性,杀死set_value函数。

一切正常,像这样的东西…

echo form_input('username', set_value('username',$user->username));

但是当使用edit_unique验证时,提交表单后该值为空。后变量是可以的,并且验证也没有错误-但是没有设置值。

有什么办法吗?

好的,我自己找到的。如果为真,则没有返回值。也许每个人都面临同样的问题……使用这个函数,它可以工作:

function edit_unique($value, $params)  {
    $CI =& get_instance();
    $CI->load->database();
    $CI->form_validation->set_message('edit_unique', "Sorry, that %s is already being used.");
    list($table, $field, $current_id) = explode(".", $params);
    $query = $CI->db->select()->from($table)->where($field, $value)->limit(1)->get();
    if ($query->row() && $query->row()->id != $current_id)
    {
        return FALSE;
    } else {
        return TRUE;
    }
}

Petra的答案很好,如果由于某种原因它不适合你,检查你的主键是否为'id',如果不是,你需要做一些改变。

改变
list($table, $field, $current_id) = explode(".", $params);
if ($query->row() && $query->row()->id != $current_id)

list($table, $field, $current_id, $key) = explode(".", $params);
if ($query->row() && $query->row()->$key != $current_id)

然后添加如下规则:

$this->form_validation->set_rules(
    'form_field', 
    'Form Label', 
    'required|trim|edit_unique[table.column.' . $edit . '.unique]'
);

其中unique是您的唯一/主键,$edit是它的值。