[eluser]eggshape[/eluser]
Hi:
View file:
Code:
// makes array from data retrieved via database and passed to view
<?php if (!empty($coverage_level) and is_string($coverage_level)) $coverage_level = explode(',', $coverage_level);
else $coverage_level = array(); ?>
// form elements
<fieldset>
<ul>
<li><label for="coverage_level">Media Coverage Level <span class="g"> * </span></label></li>
<li><span><em>Check all that apply</em></span></li>
<li><input tabindex="1" id="coverage_level[]" name="coverage_level[]" type="checkbox" value="none" <?php if (in_array('none', $coverage_level)) echo 'checked="checked"'; else echo $this->validation->set_checkbox('coverage_level', 'none'); ?> /> None</li>
<li><input tabindex="2" id="coverage_level[]" name="coverage_level[]" type="checkbox" value="national" <?php if (in_array('national', $coverage_level)) echo 'checked="checked"'; else echo $this->validation->set_checkbox('coverage_level', 'national'); ?> /> National</li>
<li><input tabindex="3" id="coverage_level[]" name="coverage_level[]" type="checkbox" value="regional" <?php if (in_array('regional', $coverage_level)) echo 'checked="checked"'; else echo $this->validation->set_checkbox('coverage_level', 'regional'); ?> ?> /> Regional</li>
<li><input tabindex="4" id="coverage_level[]" name="coverage_level[]" type="checkbox" value="local" <?php if (in_array('local', $coverage_level)) echo 'checked="checked"'; else echo $this->validation->set_checkbox('coverage_level', 'local'); ?> /> Local</li>
<?php if (isset($this->validation->coverage_level_error)) : ?>
<li class="error"><?php echo $this->validation->coverage_level_error; ?></li>
<?php endif; ?>
</ul>
</fieldset>
Controller:
Code:
public function validate()
{
if (!empty($_POST['coverage_level']))
{
/* Can't have 'none' and any other selection;
if user does select 'none' and something else, set the validation
error and generate the view again (return NULL to exit the method and
prevent submit().
*/
if (in_array('none', $_POST['coverage_level']) and count($_POST['coverage_level']) > 1)
{
$this->validation->coverage_level_error = 'Planned Media Coverage is invalid';
$this->index();
return;
}
// flatten array for DB insertion; you can tell this DB is not completely atomic =)
$_POST['coverage_level'] = implode(',', $_POST['coverage_level']);
}
$this->submit();
}
public function submit()
{ /* submit method contains code snippet: $this->validation->run() to handle the other fields and rules */}
That works for me. I use this strategy when I want to validate dynamic or *special* fields on the fly, depending on the choices the user makes or does not make. It basically involves running your own validate() method which sets the custom validation rules and then run the CI validate function on submit.
EDIT: I should be clear that the form's action is "controller/validate"...validate() is called on form submission and not submit(). And I use the default validation file for 1.5.4