Codeigniter: array múltiple en formularios.
By josepgarcia on Lun, 12/26/2011 - 12:11
Ejemplo de validación de formularios con CodeIgniter y arrays múltiples.
View: welcome.php
<?php echo validation_errors('<div class="msgerror">', '</div>'); ?>
<form action="" method="post" >
<input type="hidden" name="totalusers" value="21" />
<?php
for ($x = 0; $x < 21; $x++) {
?>
<p>
<label >Nombre de usuario:</label>
<input type="text" name="user[<?php echo $x; ?>][login]" value="<?php echo set_value('user[' . $x . '][login]'); ?>" />
</p>
<p>
<label>Email:</label>
<input type="text" name="user[<?php echo $x; ?>][email]" value="<?php echo set_value('user[' . $x . '][email]'); ?>" />
</p>
<?php
}
?>
<input type="submit" value="Enviar" />
</form>
Controller: welcome.php
function index() {
$this->load->model('Welcome_model');
//$this->output->enable_profiler(TRUE);
if ($_POST) {
$totalusers = $this->input->post('totalusers');
} else {
$totalusers = 0;
}
$rules = $this->Welcome_model->formarray_rules($totalusers);
$this->form_validation->set_rules($rules);
if ($this->form_validation->run()) {
}
$this->load->view('formarray');
}
Model: welcome_model.php
function formarray_rules($total=0) {
$array = array();
for ($x = 0; $x < $total; $x++) {
$array[] = array(
'field' => 'user[' . $x . '][login]',
'label' => 'Nombre de usuario ' . ($x + 1) . ' ',
'rules' => 'required|trim'
);
$array[] = array(
'field' => 'user[' . $x . '][email]',
'label' => 'Email ' . ($x + 1) . '',
'rules' => 'required|valid_email|trim'
);
}
return $array;
}
Categoría:
Añadir nuevo comentario