2

I have a template in Mojolicious used as a frontend for a SQL-database. To toggle a bool-value (yes=1/no=0) I am using an input type of checkbox.

This is the code from the template:

    <input type="checkbox" name="reinigung_ja" id="reinigung_ja" value="1" 
        <%= $rs->reinigung_ja ? 'checked' : ''; %>
    > Reinigung <br>

It works fine to both view the present state of the reinigung_ja field in the database and to toggle it from no to yes. But it fails to toggle from yes to no since no parameter is send, if the checkbox is unchecked.

My present workaround is this code in the controller:

  my $fields;
  foreach ($c->req->body_params->param) {
      $fields->{"$_"} = $c->req->body_params->param("$_");
  }
  # Workaround starts here ...
  if (not exists $fields->{'reinigung_ja'}) {
      $fields->{'reinigung_ja'} = 0;
  }
  # end of workaround;
  $rs->update($fields);

I wonder if there is not a better solution?

Miller
  • 34,962
  • 4
  • 39
  • 60
lanti
  • 529
  • 3
  • 15

2 Answers2

3

You could initialize a default and then update it, like so:

# Initialize defaults
my $fields = {
    'reinigung_ja' => 0,
};

for ( $c->req->body_params->param ) {
    $fields->{$_} = $c->req->body_params->param($_);
}

$rs->update($fields);

This is slightly less code, but I'm not sure which is a better pattern. If you look for it explicitly not being there, the code is fairly readable.

Miller
  • 34,962
  • 4
  • 39
  • 60
zerodiff
  • 1,690
  • 1
  • 18
  • 23
  • Thanks zerodiff, your proposal is definitely a progress since better readable. Unfortunately it does not solve the problem of having information about that checkbox in two different files. So each time I add a checkbox to the template, I would have to update the controller. – lanti Aug 26 '14 at 06:09
  • 1
    Have you considered adding hidden fields in your form with meta-information about checkboxes? This could be JSON or other regularly formatted information for initialization. – zerodiff Aug 26 '14 at 15:04
  • Sounds promising @zerodiff - thanks! Just found [this example](http://stackoverflow.com/questions/2697299/asp-net-mvc-why-is-html-checkbox-generating-an-additional-hidden-input) – lanti Aug 26 '14 at 18:43
1

Thanks to @zerodiffs comment I found the following solution.

<input type="checkbox" name="reinigung_ja" id="reinigung_ja" value="1" 
  <%= $rs->reinigung_ja ? 'checked' : ''; %>
> 
<input type="hidden" name="reinigung_ja"  value="0" > 

Although a bit wired it is much better than my workaround, since it frees the controller from the initialization of the fields. Anything is now in the template.

lanti
  • 529
  • 3
  • 15