[eluser]Iverson[/eluser]
[quote author="Too Pixel" date="1226822978"]Your idea of having a form dropdown helper from DB results is good, but I don't like much that it needs to have SQL commands in a view. What better solution can we think of?[/quote]
I agree. I was thinking the same thing. I too like the idea though so this might be a little better implementation. I separated the actual data manipulation from the display part. In your controller (I would probably run this in a model), you would run...
Code:
$form_data = form_dropdown_data('prova', "SELECT id,c_txtitaliano FROM categorie")
Then you could send your form to your view...
Code:
$form_display = form_dropdown_display($form_data);
if($form_display)
{
echo $form_display;
}
Helper File
Code:
function form_dropdown_data($name = '', $sql, $selected = array())
{
$CI =& get_instance();
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"' : '';
$query=$CI->db->query($sql);
return $query->result_array();
}
function form_dropdown_display($data, $extra = '')
{
// Only do the work if we have at least one result
if (count($data) > 0)
{
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($data as $row)
{
$values = array_values($row);
if (count($values)===2)
{
$key = (string) $values[0];
$val = (string) $values[1];
//$this->option($values[0], $values[1]);
}
$sel = (in_array($key, $selected))?' selected="selected"':'';
$form .= '<option value="'.$key.'"'.$sel.'>'.$val."</option>\n";
}
$form .= '</select>';
return $form;
}
else
{
return FALSE;
}
}