Wow… I’ve just spent forever working out how to do this and reading lots of posts that seemed very confusing for quite a while…
So here, while it is fresh in my head, is the bullet point summary of how to read and write boolean values to Checkboxes.
Background Information
In following why it is done this way, there are a couple of things to be aware of:
-
The result of an HTML
<checkbox>
tag’s setting isn’t the “value” attribute like HTML<input>
tags, they have a value representing their “checked” attribute. -
Hence if you want to understand the value being represented by your checkbox, you can’t display
{{checkbox_name.check.value}}
, you can only display{{checkbox_name.checked}}
… and by default this has values oftrue
andfalse
within Wappler, rather than1
and0
. -
If you set the “Static Value” field of the checkbox, then this is the value that will be passed through to your Server Action when the box is checked. However, no value is passed through when the box is unchecked!
-
Therefore you have to set a “default” value for your checkbox field on the Server Action side… so this is the value to pass to the database when the checkbox is unchecked.
-
In your database structure, in mySQL, you will probably have a field of type
boolean
which takes values0
and1
-
Hence the method outlined below maps the
checked
andunchecked
values in HTML to and from the0
and1
values used in the database. -
How to work will also vary slightly depending on whether you have a standalone
<checkbox>
or one of the “Bootstrap 4 Container” based ones contained in a checkbox group or custom switch structure.
Still with me?
While this all sounds complex, what you need to do is actually quite simple:
Writing Information To the Database
(If you don’t have a checkbox group or custom switch container for the checkbox, perform the actions listed to be on the Bootstrap 4 Container directly on the <checkbox>
element instead.
- On the Bootstrap 4 Container set Checkbox Static Value = 1
- In your Server Action, set the $_POST variable to be of type Boolean
- In the Server Action database update action, set your boolean field to be updated to the value {{$_POST.your_fieldname.default(0)}}
Reading Information From the Database
- On the Bootstrap 4 Container, set the Dynamic Attribute “Checked” to the field value being returned by your database via the Server Connect element.
For more Information
See:
How to bind the value to checkbox
Last updated: