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
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    Flexbox Equal Height Columns

    Flexbox was supposed to be the pot of gold at the long, long rainbow of insufficient CSS layout techniques.  And the only disappointment I've experienced with flexbox is that browser vendors took so long to implement it.  I can't also claim to have pushed flexbox's limits, but...

  • By
    CSS Rounded Corners

    The ability to create rounded corners with CSS opens the possibility of subtle design improvements without the need to include images.  CSS rounded corners thus save us time in creating images and requests to the server.  Today, rounded corners with CSS are supported by all of...

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!