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
    5 Awesome New Mozilla Technologies You&#8217;ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • By
    jQuery Wookmark

    The first thing that hits you when you visit Pinterest is "Whoa, the columns are the same width and the photos are cut to fit just the way they should."  Basic web users probably think nothing of it but as a developer, I can appreciate the...

  • By
    WebKit Marquee CSS:  Bringin&#8217; Sexy Back

    We all joke about the days of Web yesteryear.  You remember them:  stupid animated GIFs (flames and "coming soon" images, most notably), lame counters, guestbooks, applets, etc.  Another "feature" we thought we had gotten rid of was the marquee.  The marquee was a rudimentary, javascript-like...

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!