Sending a Value for Unchecked Checkbox on Database Insert / Update
Intro
In many cases you need to use checkboxes in the forms used to insert or update data in the database. Due to the nature of the checkboxes and how they work, when a checkbox is not checked it won’t send a value when your form is submitted.
This can be a problem if you want to send a false
or 0
(or any other) values to your database when your checkboxes are not checked.
With Wappler you can do this easily on the server-side directly in the insert or update steps.
Checkbox setup
We have an insert record form on the page, which contains a checkbox:
We want to insert 1
when the checkbox is checked and 0
when it’s not checked.
The first thing we need to do is to add a value to it, this is the value which will be inserted when the checkbox is checked. Select the checkbox and in the static value field enter 1
:
And we are done setting up the checkbox.
The value that will be sent to the database when the checkbox is not checked should be configured in the API Action (Server Action) used to insert the form data in the database.
Server-Side Setup
Open your insert record API Action (Server Action):
Then select the insert step and click Insert Options:
This is our checkbox input:
Double click its value and click the dynamic data picker:
Click the data formatter button:
And then right click your expression, open General and select Default:
The Default formatter is used to send a default value, when no value is sent. This is exactly what we need, as you already know the checkbox won’t send any value if not checked.
Enter the value that should be stored in the database if the checkbox is not checked. We enter 0
:
Then Click Select:
Click Select to apply the formatting to the value:
And click OK:
You are done. When you check your checkbox, it will send the value 1
to the database and when it’s not checked it will send 0
.