For this kind of thing I use this structure:
<?php
$registro['factura'] = 1; // $comisionista->factura;
$field = array(
'name' => 'factura',
'label'=>'Factura de comisionista:',
'default' => 0,
'values' => array( 1 => 'SI', 0 => 'NO'),
);
echo form_label( $field['label'], $field['name']);
foreach ($field['values'] as $option_value => $option_label) :
echo form_radio(
$field['name'],
$option_value,
(
set_value($field['name'], (
(isset($registro[$field['name']]) && $registro[$field['name']] != NULL) ?
$registro[$field['name']] :
$field['default'])
) == $option_value)
);
echo $option_label." ";
endforeach;
?>
In the array $registro
come the values of the record (what is in the database).
In the array $field
I define:
- name,
- label,
- default value
- the array of possible values:
valor => etiqueta
.
After printing the global label of the field, I go through the possible values (field options) and print the form_radio
with the following options:
form_radio('nombre', 'valor', 'true si está seleccionado')
It is the "if selected" the most curled part, for this we use set_value
that has the form:
set_value("nombre", "defult")
If the field "name" already has value (after a form_validation->run()
) that value is assigned, if it is not like that in the second parameter we indicate the default that is in case it is the first time you access the form, here what we do, to know what value "default" to use, is to verify that "name", the name of the field, exists between the values of $registro
if it is so we use that value, if it does not exist we use the default of the field defined in $field
.
With which setvalue will have one of these values:
the value set since the last post (if form_validation->run()
fails)
the value saved in $registro
the default value for this field defined in $field
This last value is the one that we compare with the value that this particular option would have, if they match the radius will go checked
if they do not match is printed without checked
.