Manage Dynamic Drop-down Lists Using TVs

Give Manager users the power to edit drop-down option lists, radio buttons and checklists to front end site visitors on forms using Template Variables.

By Bob Ray
December 7, 2021
Manage Dynamic Drop-down Lists Using TVs

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? One easy way to do that is with a regular text TV and a simple Snippet to generate the drop-down list HTML for the front end. (As with many things in MODX, this is not the only way.)

This technique enables Manager users to edit a set of options in a comma-separated list within a Template Variable (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:


/* 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).

Bob Ray is the author of the MODX: The Official Guide and dozens of MODX Extras including QuickEmail, NewsPublisher, SiteCheck, GoRevo, Personalize, EZfaq, MyComponent and many more. His website is Bob’s Guides. It not only includes a plethora of MODX tutorials but there are some really great bread recipes there, as well.