form_radio()

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

Description

Generates an HTML radio button input element. Radio buttons allow users to select exactly one option from a group of choices.

Unlike checkboxes, radio buttons always submit a value to the server, provided one in the group is selected.

Parameters

Parameter Type Description
$name string The name attribute for the radio button element. All radio buttons in a group must share the same name.
$value string|bool|int (optional) The value submitted when this radio button is selected. Defaults to empty string.
$checked mixed (optional) Whether this radio button 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 radio button input element.

Example Usage

Imagine you're building a task manager where users can select a priority level. Here's how radio buttons work in Trongate:

1. Creating a Radio Button Group

In your view, you typically create multiple radio buttons with the same name:

2. In Your Controller

The controller handles both displaying and processing radio buttons:

Flexible Checked Parameter

The $checked parameter accepts various truthy/falsy values, making comparisons easy:

Key Differences from Checkboxes

Radio buttons don't need the complex conversion patterns that checkboxes require.

Simple Examples

Basic radio button (unchecked):

Checked radio button:

With comparison logic (common pattern):

Working with Radio Button Groups

Radio buttons work in groups where only one can be selected. Here's a complete example:

Common Attributes

Add HTML attributes as needed:

Form Submission Behavior

When a form with radio buttons submits:

**Important:** If none of the radio buttons in a group are checked, the field will not be present in the `$_POST` array. The post() function with the second parameter set to `true` (XSS cleaning) handles this gracefully by returning an empty string ('').

Database Schema

Store radio button values as strings or enums in your database:

Quick Reference

Element View Code To View (Re-population) To Database (Processing)
Radio Button form_radio('field', 'value', $selected === 'value') post('field', true) post('field', true)
Checkbox form_checkbox('field', 1, (bool) $checked) (bool) post('field', true) (int) (bool) post('field', true)
Text Input form_input('field', $value) post('field', true) post('field', true)

Remember: Radio buttons use the same string value for both views and databases. The main challenge is determining which radio button should be checked when displaying the form.