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
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    MooTools Zebra Table Plugin

    I released my first MooTools class over a year ago. It was a really minimalistic approach to zebra tables and a great first class to write. I took some time to update and improve the class. The XHTML You may have as many tables as...

  • By
    CSS Columns

    One major gripe that we've always had about CSS is that creating layouts seems to be more difficult than it should be. We have, of course, adapted and mastered the techniques for creating layouts, but there's no shaking the feeling that there should be a...

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!