[eluser]Chad Fulton[/eluser]
Hello!
The problem here lies in the way that the Form_validation class works. It
only checks for group rules if there are
no defined rules when the run() function is called.
So, the first time you're calling $this->form_validation->run('accidentForm'), the function sees that there are no defined rules, and the sets rules based on the rules group accidentForm.
Then, the second time you call $this->form_validation->run('locationForm'), the function sees that there are defined rules, and so validates using the already-defined rules (which happen to be the accidentForm rules).
There are a couple of ways I've found to deal with this problem, and you may like one better than another depending on how you want the validation to work. They all involve extending the Form_validation library.
The way I've settled on is to extend the Form_validation class by adding an additional function set_group_rules(). This function allows me to explicitly add groups of rules.
So, you could do:
Code:
// This will validate both sets of rules at the same time
$this->form_validation->set_group_rules('accidentForm');
$this->form_validation->set_group_rules('locationForm');
if($this->form_validation->run() == FALSE) {
...
}
Or, you could do this:
Code:
// This will validate the 'accidentForm' first
$this->form_validation->set_group_rules('accidentForm');
if($this->form_validation->run() == FALSE) {
...
}
// Now we add the 'locationForm' group of rules
$this->form_validation->set_group_rules('locationForm');
// And now we validate *both* sets of rules (remember that the accidentForm rules are still
// there), but it doesn't necessarily matter, since it will simply redo the 'accidentForm'
// validation while also doing the 'locationForm' validation
if($this->form_validation->run() == FALSE) {
...
}
Below is the code for the extended Form_validation class, saved in the application libraries folder as MY_Form_validation.php
Code:
class MY_Form_validation extends CI_Form_validation {
/**
* Set Rules from a Group
*
* The default CodeIgniter Form validation class doesn't allow you to
* explicitely add rules based upon those stored in the config file. This
* function allows you to do just that.
*
* @param string $group
*/
public function set_group_rules($group = '') {
// Is there a validation rule for the particular URI being accessed?
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
if ($uri != '' AND isset($this->_config_rules[$uri])) {
$this->set_rules($this->_config_rules[$uri]);
return true;
}
return false;
}
}