Reputation: 1112
I am doing a validation using Code Igniter. I have a simple form which used to create / update a product record.
public function productSave($params) {
if (!$this->validate($params)) {
return FALSE;
}
$id_col_value = $params['product_id'];
if ($id_col_value) {
// update
$this->db->where("product_id", $id_col_value);
return $result = $this->db->update("product", $params);
} else {
// insert
return $result = $this->db->insert("product", $params);
}
}
My validation function looks like this,
protected function validate($params) {
$this->form_validation->set_rules("name", "", "trim|required");
$this->form_validation->set_data($params);
if ($this->form_validation->run() == FALSE){
$errors = $this->form_validation->error_array();
if ( $errors ){
return FALSE;
}
}
return TRUE;
}
When inserting (when product_id
is null) it validates. But when we have a product_id
it does not validates.
My payload ($params
) looks like this,
Array
(
[product_id] => 1 // this is NULL when we do inserting
[name] => Test Name
)
I can't figure out what I am doing wrong here and why the validation not work for updating. I use the same code for both cases.
Please Help! Thanks in advance!
Upvotes: 0
Views: 62
Reputation: 1112
I figure it out.
"We have to call the set_data() method before defining any validation rules."
Which is in the Documentation of CI.
So, basically, I call $this->form_validation->set_data($params);
first
and then, I call $this->form_validation->set_rules("name", "", "trim|required");
.
This will solve the problem.
Hope this helps anyone with the same error!!!
Upvotes: 1
Reputation: 1231
Check your params
array. I have checked it using $params = array("product_id" => 34, "name" => "Test Name")
& it's working perfectly.
If you have no inserted data with that product_id, it will not work. Suppose you have passed product_id=3
& this id is not available in table. Then how should it work?
Upvotes: 0