PHP Form Helper — Quick & Easy SELECT Dropdowns

By  on  

One of the most time-consuming parts of my job is creating web forms. PHP web forms generally aren't difficult but they take a lot of time. Any time I can save when creating web forms is great, so I've created a helper function for creating HTML <select> elements.

The Code

function form_select($name,$options,$selected = '',$params = '')
{
    $return = '<select name="'.$name.'" id="'.$name.'"';
    if(is_array($params))
    {
        foreach($params as $key=>$value)
        {
            $return.= ' '.$key.'="'.$value.'"';
        }
    }
    else
    {
        $return.= $params;
    }
    $return.= '>';
    foreach($options as $key=>$value)
    {
        $return.='<option value="'.$value.'"'.($selected != $value ? '' : ' selected="selected"').'>'.$key.'</option>';
    }
    return $return.'</select>';
}

The Explanation

The function accepts four arguments, two required, two optional. Arguments include:

  • $name - name (doubles as the id) of the select element. Required.
  • $options - a key=>value array of keys (Wisconsin) and values (ex: WI). Required.
  • $selected - the previously selected value (ex: WI). Optional.
  • $params - an key=>value array or string ('onchange="alert('you changed me!');"'). Optional.

The Usage

echo 'State: ', form_select('state', array('Michigan'=>'MI', 'Minnesota'=>'MN', 'Wisconsin'=>'WI', 'Wyoming'=>'WY'),'WY', 'onchange="alert(\'Change\');"');

Would you use the script? Do you know any ways to improve it? Share!

Recent Features

  • By
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

  • By
    MooTools ASCII Art

    I didn't realize that I truly was a nerd until I could admit to myself that ASCII art was better than the pieces Picasso, Monet, or Van Gogh could create.  ASCII art is unmatched in its beauty, simplicity, and ... OK, well, I'm being ridiculous;  ASCII...

  • By
    Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

Discussion

  1. A very handy function. However a lot of frameworks these days offer form helper objects which have something like this already defined… and other handy things too.

  2. Chuck

    I have created a simple form creator script (I need to polish it and release it). It does the following:

    Step 1: Textarea that accepts comma delimited input for input names (First Name, Last Name, Address, etc.)

    Step 2: Presented with a form that lists all of the above inputs with radio options for type of form (Text Box, Radio, Password, Hidden, etc.)

    Step 3: Prints out the fields into a textbox for copy-paste.

    *I plan on making a dropdown so you can choose the ‘template’ you wish to populate the form with. Right Now it writes out:

    .label for=’input name(lowercased and underscored)’>input name(uppercased)-label>
    .input type=’etc’ name =’input name(lowercased and underscored)’ value=” />
    .br class=’clear’ />

    This makes creating a css form with multiple values take less than 5 minutes. Then you can do some quick CSS tweaks and be done with it.

  3. Sounds good Chuck — be sure to let me know when it’s released!

  4. c_wd

    an example of usage would make this more friendly.

    $hours4select = array(1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>10, 11=>11, 12=>12);
    
    echo form_select('class_time_hour', $hours4select);
    
  5. David,
    Thank you very much for the helper function. I will use it in my projects.

    In the earlier posts, I read that @Chuck mentioned about a simple form creator script. In fact, such a tool already exists and I use that for my projects. This tool is called: Form & PHP/MySQL Generator (FPMG) & you can visit it at: http://www.fpmg.co.cc

    So I don’t see a point in reinventing the wheel, unless the functionality that @Chuck wants to implement, differs greatly.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!