Scripting Radio Buttons

I use Perl’s HTML::Template module a lot. It allows you to write web pages that are dynamically modified by the controlling Perl CGI/mod_perl application.

Most of my applications fill in forms from values in a database. This is easy enough when you are filling text fields, but if you ever use radio buttons, things kind of fall down.

I’ve found a way around this. Let’s say you have a status field that can have three values:

  • active
  • blocked
  • retired

So in Perl I define three constants:

  use constant STATUS_ACTIVE => 'active';
  use constant STATUS_BLOCK => 'block';
  use constant STATUS_RETIRE => 'retire';

Then in the template, I have something like this:

  <input type="radio" name="status"
   <!-- /TMPL_IF -->
  value="active" />Active

  <input type="radio" name="status"
   <!-- /TMPL_IF -->

  value="block" />Blocked

  <input type="radio" name="status"
   <!-- /TMPL_IF -->
  value="retire" />Retired

If the status variable is $account->status, say, I’d use:

   STATUS_ACTIVE => ($account->status eq STATUS_ACTIVE),
   STATUS_BLOCK =>  ($account->status eq STATUS_BLOCK),
   STATUS_RETIRE => ($account->status eq STATUS_RETIRE)

and, magically, the template picks up the right value.

If the status variable isn’t set to one of the three predefined values, you get a radio group that none of the values is selected. You might wish to think about how you’d deal with that, perhaps setting a safe default.

Leave a Reply

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