Snippets

Checked Radio Buttons

gourmet fare

Sticky Radio Buttons

How can you make radio buttons "sticky" across page refreshes?

redhen asks...

I have three radio buttons to sort items on a page, like this:

<form action="[[~[[*id]]]]" method="POST">
   <input type="radio" name="sort_method" id="itemno" value="itemno" onChange="this.form.submit();" />Sort by Name
   <input type="radio" name="sort_method" id="height" value="height" onChange="this.form.submit();" />Sort by Height
   <input type="radio" name="sort_method" id="width" value="width" onChange="this.form.submit();;" />Sort by Width
</form>

The sorting works perfectly, but the radio button doesn't stay checked. I would like it to show which sorting method is active.

The Solution

bobray says...

Here's one way to do it - the form:

<form action="[[~[[*id]]]]" method="POST">
   <input type="radio" name="sort_method" [[+itemno_checked]] id="itemno" value="itemno" onChange="this.form.submit();" />Sort by Name
   <input type="radio" name="sort_method" [[+height_checked]] id="height" value="height" onChange="this.form.submit();" />Sort by Height
   <input type="radio" name="sort_method" [[+width_checked]] id="width" value="width" onChange="this.form.submit();;" />Sort by Width
</form>

In the part of the code that processes the form on submission, do this:

$checked = 'checked="checked"';
// Assuming that $val is the submitted value of the checkbox
$modx->setPlaceholder($val . '_checked', $checked);

Because the other placeholders aren't set, they'll be stripped out.

What's the Story

Placeholders are a handy way of carrying data across pages when a snippet has used POST or another of PHP's global input methods to collect the input from a page.

Always keep in mind that input from any source is dangerous, and should always be validated. In a case like this you could add:

$sortby = 'itemno';
$checked = 'checked="checked"';
if (isset($_POST['sort_method']) && (! empty($_POST['sort_method']))) {
    $sortby = $_POST['sort_method'];
}
// validate POST input
$sortmethods = array('itemno','height','width');
if(!in_array($sortby, $sortmethods)) $sortby = 'itemno';
$modx->setPlaceholder($sortby . '_checked', $checked);
// ... code to generate sorted list