[eluser]Glazz[/eluser]
Hey there !
Since the form_dropdown() doesn't accept arguments to be arrays, at least on the first argument i've modified the helper function.
Code:
function form_dropdown()
{
// Get the arguments passed.
//
$args = func_get_args();
// Declare the variables.
//
$name = ( isset($args[0]['name']) ? $args[0]['name'] : ( isset($args[0]) ? $args[0] : false ) );
$options = ( isset($args[0]['options']) ? $args[0]['options'] : ( isset($args[1]) ? $args[1] : array() ) );
$selected = ( isset($args[0]['selected']) ? $args[0]['selected'] : ( isset($args[2]) ? $args[2] : array() ) );
$extra = ( isset($args[0]['extra']) ? $args[0]['extra'] : ( isset($args[3]) ? $args[3] : false ) );
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
if (is_array($val) && ! empty($val))
{
$form .= '<optgroup label="'.$key.'">'."\n";
foreach ($val as $optgroup_key => $optgroup_val)
{
$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
}
$form .= '</optgroup>'."\n";
}
else
{
$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';
$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
}
}
$form .= '</select>';
return $form;
}
The functionality is the same as before, but now you can have something like this:
Code:
$data = array(
'name' => 'your input name',
'options' => 'your item options'
'selected' => 'the selected value'
);
form_dropdown($data, null, null, 'class="my class" id="country"');
I needed this because i'm creating my inputs on the controller, and then i'm adding the class style on the view, mainly because of templates, and i didnt want to have 3 more variables passed to the view so i could populate the dropdown ( $name, $data and the selected value ) and add the style needed !
To use this just create a new file in your
application/helper folder called
MY_form_helper.php and paste in inside that file and thats it =)
Don't know if this is usefull for someone, but here it is anyway =)