Dynamic TV-Based Drop-down Lists

Create a simple snippet to show TV-based drop-down lists in the front end.


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:

<?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).



Comments (0)


Please login to comment.

  (Login)