Reputation: 3790
I'm having an issue with a module that I am writing (Shop-products module).
When I run form validation once, everything is fine. However when I edit()
the product and run the validation runs again (which is what I expect) but it returns an error saying that the slug must be unique.
How can I change the validation rule for the edit mode to ignore checking the existing row/field?
Below is a subset of my controller class:
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()) { }
}
Upvotes: 1
Views: 289
Reputation: 2057
its because you've saved the slug
in your DB and upon editing it. it returns an error because its referring to itself. you can try to make a call_back function
upon updating your new value, that function then connects to the model and runs a query checking the new value. You can try something like this:
primary key - auto increment
you can just use it to find the specific slug that is to be updated, you can check the slug
uniqueness but not the 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
Upvotes: 4