【问题标题】:Form validation returns non-unique slug error after edit()表单验证在 edit() 后返回非唯一的 slug 错误
【发布时间】:2013-06-19 02:25:17
【问题描述】:

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

当我运行一次表单验证时,一切都很好。但是,当我 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()) { }
}

【问题讨论】:

  • edit() 是做什么的?
  • 对不起,这是我的产品控制器上的编辑功能
  • 是的,我如何仍然拥有编辑的验证规则,但将其设置为忽略 id=?? 的记录?

标签: php codeigniter validation


【解决方案1】:

这是因为您已将 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多