CodeIgniter Forums
Form Helper - Select Lists/Menu's - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=22)
+--- Thread: Form Helper - Select Lists/Menu's (/showthread.php?tid=1867)



Form Helper - Select Lists/Menu's - El Forum - 07-02-2007

[eluser]Phil Sturgeon[/eluser]
Well we have form_dropdown but nothing for making lists? *unhappyface*

Try:

Code:
function form_list($name = '', $options = array(), $selected = array(), $extra = '')
{

    if ($extra != '') $extra = ' '.$extra;
    
    // converts to an array if it is not
    if(!is_array($selected)) $selected = array($selected);
    
    // If not set, will default
    if(!strpos('size=', '#'.$extra)) $extra .= ' size="5"';
    
    $form = '<select name="'.$name.'"'.$extra.">\n";
    
    foreach ($options as $key => $val)
    {
        $sel = (!in_array($key, $selected)) ? '' : ' selected="selected"';
        
        $form .= '<option value="'.$key.'"'.$sel.'>'.$val."</option>\n";
    }

    $form .= '</select>';
    
    return $form;
}


Useage:

Code:
form_list('supervisorID[]', array(1 => 'Foo', 2 => 'Bar', 3 => 'Stuff'), array(1, 3), 'size="5" multiple="multiple"');

This is not hugely different from the form_dropdown code but allows you to pass strings or arrays as the selected values meaning multiple selections are possible. Also if no size param is set in $extra then it will add a size of 4 in, just for the hell of it.

Hope this helps someone?


Form Helper - Select Lists/Menu's - El Forum - 10-09-2012

[eluser]MasterHernan[/eluser]
I know this is an old post but since Google has this thread in the top results when searching for a way to do a select list with form helper. I figured it would help if I post a different solution using form_dropdown().

To get a list, add the size attributes in the extra parameters of the function.

Code:
form_dropdown($name, options(), selections(), $extras);

Example:

Code:
form_dropdown('shirts', array('small' => 'Small Shirt', 'medium' => 'Medium Shirt'), '', 'size=5');