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

时间:2013-06-19 02:25:17

标签: php codeigniter validation

我正在编写我正在编写的模块(Shop-products模块)。

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

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

以下是我的控制器类的一个子集:

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

1 个答案:

答案 0 :(得分:4)

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

<小时/> 的更新
您永远不应该更新 ID ,特别是如果它只是primary key - auto increment您可以使用它来查找要更新的特定slug,您可以检查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