|
Dropdown menus that let you choose between different options that result from a database query are often needed when building web-pages. To create them using patTemplate is quit easy. Take a look at the following template: 001 <patTemplate:tmpl name="page"> 002 <html> 003 <head> 004 <title>patTemplate Example</title> 005 </head> 006 <body> 007 <table border="0"> 008 <tr> 009 <td>Choose your superhero:</td> 010 <td> 011 <select size="1" name="superhero"> 012 <option value="none">Please choose...</option> 013 <patTemplate:tmpl name="dropdown_entry" type="condition" conditionvar="selected"> 014 <patTemplate:sub condition="no"> 015 <option value="{id}">{superhero}</option> 016 </patTemplate:sub> 017 <patTemplate:sub condition="yes"> 018 <option value="{id}" selected="yes">{superhero}</option> 019 </patTemplate:sub> 020 </patTemplate:tmpl> 021 </select> 022 </td> 023 </tr> 024 </table> 025 </body> 026 </html> 027 </patTemplate:tmpl> If you ignore the HTML code, the template is quite simple. Of course there is one template for the complete page, like it should be in every file. This template also contains the actual <select> tag, which craetes a HTML drop down menu. Furthermore there is a second template called dropdown_entry. This template will be used to dynamically build the drop down list. The template type is set to condition as there may be two modes for each entry. Eitherit is selected by default or it isn't. To fill the drop down menu with entries resulting from database query you'll need the following code:
01 <?PHP 02 $tmpl->readTemplatesFromFile( "myTemplate.tmpl" ); 03 04 $defaultId = 19; 05 06 $query = "SELECT id, superhero FROM heroes ORDER BY superhero"; 07 $result = mysql_query( $query ); 08 09 $entries = array(); 10 while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) 11 { 12 // determine, wether entry should be selected by default 13 if( $row["id"] == $defaultId ) 14 $row["selected"] = "yes"; 15 else 16 $row["selected"] = "no"; 17 18 // add the entry to all other entries 19 array_push( $entries, $row ); 20 } 21 // add all entries to the drop down menu 22 $tmpl->addRows( "dropdown_entry", $entries ); 23 // display the page 24 $tmpl->displayParsedTemplate( "page" ); 25 ?> This will display a drop-down menu with all entries in the table heroes, the superhero with the id 19 will be selected by default. Tip
Switching to radio groups If you are using the technique of condition templates to print out to different versions for selected and unselected entries, you may switch the drop-down menu to a radio group without modifying the PHP code.
|