Welcome Guest, Not a member yet? Register   Sign In
helper to build a dropdown whose contents come from mysql
#1

[eluser]Flemming[/eluser]
Hi gang, I'd been puzzling over this:

Every page of my project includes a <select> box of 'locations' - the contents come from a mysql query.

The dropdown DOES need to be created afresh on each page as it may have a different item selected each time.

This is what I did (in a helper):
Code:
function buildAreasDropdown()
    {
        // we MAY have passed a value (the area option selected)
        $numargs = func_num_args();
         if ($numargs > 0) {
             $selected = func_get_arg(0);
         }
        
        $ci = & get_instance();
        $ci->db->group_by('Area');
        $areas = $ci->db->get('properties');
        
        $output = "<select name=\"location\" id=\"location\" class=\"listMenu\">\n";
        $output.= "<option value=\"\">Any</option>";
        foreach($areas->result() as $row){
            $output.= "<option value=\"$row->Area\"";
            if(isset($selected)){
                if($selected == $row->uid){
                    $output.=" selected=\"selected\"";
                }    
            }
            $output.=">$row->Area</option>\n";
                
        } // end foreach
        
        $output.= "</select>\n";
        
        return $output;
    }

Then I auto load the helper and simply call buildAreasDropdown() from any of my views. If I call it with a value: buildAreasDropdown('London'), it will do selected='selected' for London.

Does anyone have a neater solution to achieve this as I'm not sure I've done it the best way?
#2

[eluser]Aken[/eluser]
Looks simple enough to me. Although I can't see why you're including a separate function when adding the selected city. You could just do
Code:
buildAreasDropdown($selected = '')
#3

[eluser]Flemming[/eluser]
thanks for the tip! :-)
#4

[eluser]frenzal[/eluser]
why not use form_dropdown and just create an array that you can pass to it




Theme © iAndrew 2016 - Forum software by © MyBB