[html-formfu] How to handle checkboxes

Dermot paikkos at googlemail.com
Wed Aug 27 15:11:59 BST 2008


2008/8/27 Carl Franks <fireartist at gmail.com>:
> 2008/8/27 Dermot <paikkos at googlemail.com>:
>> Hi,
>>
>> As a first post I would like to say what a great framework FormFu is.
>>
>> I have a feeling my first question is not the smartest to ask but here goes.
>>
>> My form has a series of checkboxs that correspond to true/false fields.
>>
>> I am doing this to
>>
>>   if ($c->model->{val} == 1) {
>>             $box->attributes->{checked} = 'true';
>>   }
>>
>>
>> This gives me a source like this
>>
>>
>> <label>Has type</label>
>> <input name="hastype" type="checkbox" checked="true" />
>>
>>
>> My query is whether this is correct HTML (4)?
>>
>> I had a look at the WC3 site and I think checked is an attribute but I
>> thought I should be getting a source like
>> <input name="hastype" type="checkbox" checked  />
>>
>> Am I using the right methods?
>
> Hi Dermot,
>
> Don't worry - this isn't a silly question at all!
>
> As Moritz said, checked="checked" is equivalent to the old `checked`,
> and should work just fine in HTML4 - it's just that our output is
> geared towards being valid xhtml.
>
> I think there's a more "correct" way of doing this, though.
> You should always be setting the Checkbox's value(), so that the
> browser knows what to send back when it's checked.
> In this case, you could just do this
>
>    $box->default( $c->model->{val} );
>
> And the Checkbox is smart enough to set checked="checked" when
> default() is the same as value().
> And if they're different, the default() will just be ignored.


Thank you both you your quick response and I can see what you mean by
being xhtml compliant. I have tried to use Carl's suggested default
method but I can't be using it correctly. I imagine I should see a
source like

<input type="checkbox" name="hastype" checked="true"/> or <input
type="checkbox" name="hastype" checked="false"/>

Here's my complete subroutine, perhaps that might explain why that
method doesn't appear to work.

use base qw(Catalyst::Controller::HTML::FormFu);
...

sub updateCheckboxes : Private {
  my ($c,$data) = @_;             # Data contains the model.
  my $form = $c->stash->{form};
  my $checkboxes = $form->get_all_elements({type => 'Checkbox'});
  foreach my $box (@{$checkboxes}) {
          my $name = $box->name;
          my $val = $data->sub_id->$name;
          $c->log->debug("Box=$box->{name} $data->sub_id->$box->name
VAL=$val");
#         if ($val && $val == 1) {
          $box->default($val);
#         }
  }
}


Thanx,
Dp.



More information about the HTML-FormFu mailing list