Dynamic Drop-Down Lists in the Front End Using a TV with MODX

You can use a drop-down list to show Manager Users options for a TV value, but what if you want to show those options in a form in the front end instead? The simplest way to do this is with a regular text TV and a simple snippet to generate the drop-down list HTML for the front end.

This technique is useful if you want to let the Manager users enter the options as a comma-separated list in the TV and show those options as a drop-down list in a front-end form.

Create a TV called DropdownOptions. The default options should be fine, although you may want to create a default value (e.g., red,blue,green or @INHERIT).

Create a snippet called “ShowDropdown” with this code:

[code language=”php”]
/* ShowDropdown snippet */
$items = $modx->getOption(‘items’, $scriptProperties, ‘No Options To Show’);
$multiple = $modx->getOption(‘multiple’, $scriptProperties, false);

/* Set the Tpl to use for each option */
$tpl = ‘ <option value="[[+item]]">[[+item]]</option>’;

/* Convert the comma-separated items to an array */
$items = explode(‘,’, $scriptProperties[‘items’]);

/* See if we’re creating a multi-select list */
if ($multiple) {
$output = ‘<select multiple="multiple">’;
} else {
$output = ‘<select>’;

/* Create the inner HTML */
foreach ($items as $item) {
$output .= "\n" . str_replace(‘[[+item]]’, trim($item), $tpl);

/* add the closing tag */
$output .= "\n</select>";

/* return the finished HTML */

return $output;

Where you want to show the drop-down HTML code, use this tag:

[[ShowDropdown? &items=`[[*DropdownOptions]]` &multiple=`0`]]

MODX will send the comma-separated list stored in the TV as a property to the snippet, which will parse it and return the HTML for your list. If you want a multi-select list, change the &multiple property value to 1.

With some minor changes, this technique could be used to produce radio options, checkboxes, or a list (ordered or unordered).

For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , | Posted under MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray is the author of MODX: The Official Guide and over 30 MODX add-on components. He hosts Bob's Guides, a source of valuable information for MODX users, and has been very active in the MODX Forums with over 19,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *