表单验证在edit()之后返回非唯一的段错误


Form validation returns non-unique slug error after edit()

我正在编写的模块(商店产品模块)有问题。

当我运行表单验证一次,一切都很好。然而,当我edit()产品并运行验证再次运行时(这是我所期望的),但它返回一个错误,说鼻涕虫必须是唯一的。

如何更改编辑模式的验证规则以忽略检查现有行/字段?

下面是我的控制器类的子集:

public function create() {
    //this works fine
    $this->form_validation->set_rules('slug', 'Slug',
     'trim|required|is_unique[shop_products.slug]');    
    if ($this->form_validation->run()) { }
}
//when this runs the validation for slug returns saying not unique
// do i need a different validation rule ??
public function edit($id = 0) {
    $this->data = $this->products_m->get($id);
    $this->form_validation->set_rules('slug', 'Slug',
     'trim|required|is_unique[shop_products.slug]');    
    if ($this->form_validation->run()) { }
}

这是因为您已经将slug保存在DB中并在编辑它时。它返回一个错误,因为它引用了自己。您可以尝试在更新新值时创建call_back function,该函数然后连接到模型并运行查询检查新值。你可以试试这样做:



你不应该更新ID,特别是如果它是一个primary key - auto increment,你可以用它来找到要更新的特定段塞,你可以检查slug的唯一性,但不能检查id if its the primary key

public function check_slug()
{
    $id = $this->input->post('id');
    $data = array('id' => $id);
    if($this->model->check_slug($data))     
        return false;
    else
        return true;
    // end if
} // end function
public function update_slug_valiation()
{
    $id = $this->input->post('id');
    $slug = $this->input-->post('slug');
    $this->form_validation->set_rules('slug', 'Slug', 'callback_check_slug');
    if($this->form_validation->run() == TRUE)
    {
        $data = array('slug' => $slug);
        if($this->model->update_slug($data))
        {
            echo "<script> alert('Slug Updated!'); </script>";
        }
        else
        {
            echo "<script> alert('Updating Failed!'); </script>";
        }
        //end if
    }
    else
    {
        echo "<script> alert('Slug is already taken'); </script>";
    }
    // end if
} // end function