Update field in validation rule
- Single Page
Posted 17 July 2012 - 21:47 PM
I want to do the following:
1 - Upon update or insert, execute some code to change the value of fields before submitting them
2 - If the process fails, display an error message
Now, looking at the forums and doc I understood that
1: Can be done using callback_before_insert and callback_before_update
BUT
2: cannot be done using callback_before_insert and callback_before_update
And
2: can be done using set_rules and passing a callback function
BUT
How can I then change the value of the form field in a set_rules callback, before submitting them (as would be done using the return $post_array of callbacks ?
Thanks in advance
Posted 18 July 2012 - 11:22 AM
I actually reply to my own post in case someone is interested by the solution.
I solved this problem by :
1 - Creating a class property in the construct (for use as a global variable in the class context)
e.g.
function __construct()
{
[indent=1]parent::__construct();[/indent]
[indent=1]$this->load->database();[/indent]
[indent=1]$this->load->library('grocery_CRUD');[/indent]
$this->myProperty = ""; // Class property used as a global variable
}
2 - In the set_rules callback, assigning the result of the process to this class property (and return true) or displaying my error message there (and return false);
e.g.
function myValidationRule($value) {
// Some process
if ($process == "OK") {
// Successful
$this->myProperty = $someResult;
return true;
}
else {
// failure
$this->form_validation->set_message('myValidationRule', $message);
return FALSE;
}
}
3 - Assigning the property to the adequate $post_array index in the callback_before_insert / callback_before_update function (that are actually called only if the set_rules succeeds).
function myCallBack($post_array, $primary_key) {
if (!empty($post_array['myField'])) {
// if field is already set just return
return;
}
else {
$post_array['myField'] = $this->myProperty;
return $post_array;
}
So :
- If my process succeeds the value is assigned to the correct field (myField) and saved
- if the process fails, an error message is displayed
Posted 19 July 2012 - 13:23 PM