Reputation: 2850
I want to pass multiple callbacks in codeigniter form validation rules.... but only one of the callbacks work
I am using this syntax in my contoller
$this->form_validation->set_rules(
array(
'field' => 'field_name',
'label' => 'Field Name',
'rules' => 'callback_fieldcallback_1|callback_fieldcallback_2[param]',
'errors' => array(
'fieldcallback_1' => 'Error message for rule 1.',
'fieldcallback_2' => 'Error message for rule 2.',
)
),
);
and the callback functions are....
function fieldcallback_1 (){
if(condition == TRUE){
return TRUE;
} else {
return FALSE;
}
}
function fieldcallback_2 ($param){
if(condition == TRUE){
return TRUE;
} else {
return FALSE;
}
}
Someone please help me out with this problem.... any other solutions regarding passing multiple callbacks in form validation rules are also appreciated...
Upvotes: 2
Views: 1664
Reputation: 489
Use serialize()
to pass multiple parameters to the form validation callback:
public function get_form_input() {
// assemble the parameters into an array, as many as you like
$aryParams = ['item_1' => $value1, 'item_2' => $item2, 'item_3' => $value3];
// serialize the array (creates a string)
$strSerializedArray = serialize($aryParams);
// pass the string to the callback
$this->form_validation->set_rules('form_field_name', 'Your Message', 'callback_validate_form_data['.$strSerializedArray.']');
}
// and, the callback function:
public function _validate_form_data($form_field, $strSerializedArray) {
// convert the string back to an array
$aryParams = unserialize($strSerializedArray);
// use the array elements, as needed
$item_1 = $aryParams['item_1'];
$item_2 = $aryParams['item_2'];
$item_3 = $aryParams['item_3'];
}
Upvotes: 0
Reputation: 8964
All validation routines must have at least one argument which is the value of the field to be validated. So, a callback that has no extra arguments should be defined like this.
function fieldcallback_1($str){
return ($str === "someValue");
}
A callback that requires two arguments is defined like this
function fieldcallback_2 ($str, $param){
//are they the same value?
if($str === $param){
return TRUE;
} else {
$this->form_validation->set_message('fieldcallback_2', 'Error message for rule 2.');
//Note: `set_message()` rule name (first argument) should not include the prefix "callback_"
return FALSE;
}
Upvotes: 2
Reputation: 540
Maybe like this?
$this->form_validation->set_rules(
array(
'field' => 'field_name',
'label' => 'Field Name',
'rules' => 'callback_fieldcallback_1[param]'),
);
// Functions for rules
function fieldcallback_1 ($param){
if(condition == TRUE){
return fieldcallback_2($param);
} else {
$this->form_validation->set_message('callback_fieldcallback_1', 'Error message for rule 1.');
return FALSE;
}
}
function fieldcallback_2 ($param){
if(condition == TRUE){
return TRUE;
} else {
$this->form_validation->set_message('callback_fieldcallback_1', 'Error message for rule 2.');
return FALSE;
}
}
Upvotes: 0