form_checkbox()

function form_checkbox(string $name, string|bool|int $value = '1', mixed $checked = false, array $attributes = []): string

Description

Generates an HTML checkbox input element. Checkboxes allow users to select or deselect a single option.

Unlike other form elements, unchecked checkboxes do not submit any data to the server.

Parameters

Parameter Type Description
$name string The name attribute for the checkbox element.
$value string|bool|int (optional) The value submitted when checked. Defaults to '1'.
$checked mixed (optional) Whether the checkbox should be checked. Default is false. Accepts true, false, 'true', 'false', 1, 0, '1', '0', 'yes', 'no', 'on', 'off'.
$attributes array (optional) HTML attributes like class, id, etc. Defaults to an empty array ([]).

Return Value

Type Description
string HTML checkbox input element.

Example Usage

Imagine you're building a task manager where users can mark tasks as complete. Here's how checkboxes work in Trongate:

1. In Your View (create.php)

Trongate Convention: Always use 1 as the checkbox value. This makes data conversion simple and consistent.

2. In Your Controller (Tasks.php)

The controller prepares data for the view and handles form submission:

Understanding Checkbox Behavior

Checkboxes work differently than other form elements:

This is HTML behavior, not Trongate. That's why you need special handling.

Flexible Checked Parameter

The $checked parameter accepts various truthy/falsy values:

The Complete Pattern

Remember these conversions:

  • For views: (bool) post('field', true) → returns true/false
  • For database: (int) (bool) post('field', true) → returns 1/0

Simple Examples

Basic checkbox with default value (unchecked):

Explicitly unchecked checkbox:

Default State: By default, checkboxes are unchecked. The third parameter $checked defaults to false, so form_checkbox('field') and form_checkbox('field', 1, false) produce identical unchecked checkboxes.

Checked checkbox:

With custom attributes:

Common Pitfalls

Avoid string values for checkboxes:

Do this instead:

Database Schema

Store checkbox values as integers in your database:

Quick Reference

The table below illustrates how checkboxes are the only form element type that requires special handling when converting between view logic and database storage.

Element View Code To View (boolean) To Database
Checkbox form_checkbox('field', 1, $checked) (bool) post('field', true) (int) (bool) post('field', true)
Radio form_radio('field', 'value', $checked) post('field', true) post('field', true)
Text Input form_input('field', $value) post('field', true) post('field', true)

Remember: Checkboxes are the only form element that needs different handling for views vs. databases. Everything else uses the same value for both.