Creating Form Elements


Now let's look at how some of the items in an HTML form can be generated by using custom PHP functions. This type of modularization means that you can use a function over and over again whenever you need to include the same type of item on a form.

Creating a Dynamic Radio Button Group

A modular routine to generate a radio button group requires three pieces of information: the name of the group, a list of values, and a list of labels. You can use an associative array to pass the values and labels to the function in one go.

Say you want to be able to generate the HTML for a radio button group by using simple code similar to the following:

 $options = array("economy"  => "Economy",                   "standard" => "Standard",                   "express"  => "Express"); $default = "economy"; $html = generate_radio_group("shipping", $options, $default); 

As you can see, this is the kind of function you are likely to use again and again when creating HTML forms, and it is very useful to build up a toolbox of similar functions to make it easy to perform common tasks. Here's how the generate_radio_group function might be implemented:

 function generate_radio_group($name, $options, $default="") {   $name = htmlentities($name);   foreach($options as $value => $label) {     $value = htmlentities($value);     $html .= "<INPUT TYPE=\"RADIO\" ";     if ($value == $default)       $html .= "CHECKED ";     $html .= "NAME=\"$name\" VALUE=\"$value\">";     $html .= $label . "<br>";   }   return($html); } 

At the heart of the function is a loop through $options that generates each <INPUT> tag in turn, giving each tag the same NAME attribute but a different VALUE attribute. The label text is placed next to each button, and in this sample function, the only formatting is to place a <br> tag between each button in the group. You could format the options in a table or in any other way you see fit.

At each step of the loop, the script compares the current value of $value with the passed-in $default value. If they match, the CHECKED attribute is included in the generated HTML. Again, spacing is important here; note that the space after CHECKED is added to the HTML string.

The $default argument is specified as optional. If generate_radio_group is called with only two arguments, none of the radio buttons will be selected by default.

HTML Entities The htmlentities function is used to replace certain characters in a string with corresponding HTML entities. Because the values of $name and $value are output inside another HTML tag, the htmlentities function is important to ensure that there are no characters in those strings that could break the tag.


Creating a Dynamic Menu

The process for creating a drop-down menu is very similar to that for creating a radio button group. Again, a loop is requiredthis time to generate an <OPTION> tag for each option in turn. The function also needs to include the <SELECT> and </SELECT> tags around the option list. The function generate_menu would look like this:

 function generate_menu($name, $options, $default="") {   $html = "<SELECT NAME=\"$name\">";   foreach($options as $value => $label) {     $html .= "<OPTION ";     if ($value == $default)       $html .= "SELECTED ";     $html .= "VALUE=\"$value\">$label</OPTION>";   }   $html .= "</SELECT>";   return($html); } 

The string returned by this function contains the entire HTML code to produce a drop-down menu that contains the supplied options. You might prefer to have the function return only the option tags and place your own <SELECT> tags around them; this would allow you to easily add a JavaScript onChange event on the menu, for instance.

Multiple Selection Items

When used with the MULTIPLE attribute, the <SELECT> form item allows a user to choose multiple options from a menu, usually by holding the Ctrl key while clicking the options. To handle more than one selection in PHP, the input name must be an array. Then when the form is posted, the elements in the array contain the values of each selected item in turn.

For example, if you create a multiple-selection menu by using the following HTML and submit it to a PHP script that contains just a print_r instruction, you see that $_POST["colors"] is an array that contains one element for each option selected:

 <SELECT MULTIPLE NAME="colors[]"> <OPTION VALUE="red">Red</OPTION> <OPTION VALUE="white">White</OPTION> <OPTION VALUE="blue">Blue</OPTION> </SELECT> 

With all three of the options selected, $_POST["colors"] contains three elements with numeric indices 0 to 2, having values red, white, and blue, respectively.

The same principle applies to any type of form input. If more than one item exists with the same name but the name ends with a pair of square brackets, an array is created in PHP with that name, containing elements for each of those items' values.

This is most useful when you're implementing a multiple-selection input using check boxes. Rather than having to give each check box a unique name, you can give each the name of an array. The array created when the form is submitted contains an element for each item checked.

The final example in this lesson involves the function generate_checkboxes, which creates a set of check boxes with the same name that can be used as an alternative to <SELECT MULTIPLE> to implement a multiple-option selection in an HTML form. The function, along with a simple example of its usage, is shown in Listing 12.4

Listing 12.4. Creating a Multiple-Option Selection Using Check Boxes
 <?php function generate_checkboxes($name,                     $options, $default=array()) {   if (!is_array($default))     $default = array();   foreach($options as $value => $label) {     $html .= "<INPUT TYPE=CHECKBOX ";     if (in_array($value, $default))       $html .= "CHECKED ";     $html .= "NAME=\"{$name}[]\" VALUE=\"$value\">";     $html .= $label . "<br>";   }   return($html); } $options = array("movies" => "Going to the movies",                  "music"  => "Listening to music",                  "sport"  => "Playing or watching sports",                  "travel" => "Traveling"); $html = generate_checkboxes("interests",                                $options, $interests); ?> <H1>Please select your interests</H1> <FORM ACTION="interests.php" METHOD=POST> <?php print $html;?> <INPUT TYPE=SUBMIT VALUE="Continue"> </FORM> 

In the function generate_checkboxes, the $default argument is an array rather than a single value; after all, more than one of the options might be selected by default. The array passed in as $default can be exactly the same array that is submitted to PHP by the HTML that this function creates.

To find out whether each check box should have the CHECKED attribute, in_array is called to see whether the current option name is in the list of default values. If $value appears anywhere in $default, the check box will be checked when the page loads.

Listing 12.4 shows this function in action, using a section of a web page that asks a user about her interests. She can select any number of items from the list, and, in this example, the script submits to itself with the options remaining checked so that the user can change her mind if she wants to.

In the array $interests created in PHP, each element is a key name from $options. If you want to find the label that corresponds to each selected option, you can reference the corresponding element from $options.



    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net