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:

View File
<?php
echo form_label('Priority Level:');
echo '<div class="radio-group">';

echo '<div>';
echo form_radio('priority', 'low', $priority === 'low');
echo form_label('Low Priority', ['for' => 'priority_low']);
echo '</div>';

echo '<div>';
echo form_radio('priority', 'medium', $priority === 'medium');
echo form_label('Medium Priority', ['for' => 'priority_medium']);
echo '</div>';

echo '<div>';
echo form_radio('priority', 'high', $priority === 'high');
echo form_label('High Priority', ['for' => 'priority_high']);
echo '</div>';

echo '</div>';
?>

2. In Your Controller

The controller handles both displaying and processing radio buttons:

PHP
<?php
class Tasks extends Trongate {
    
    public function create(): void {
        $update_id = segment(3, 'int');
        
        if ($update_id > 0 && REQUEST_TYPE === 'GET') {
            // Editing existing task
            $task = $this->db->get_where($update_id, 'tasks');
            $data['priority'] = $task->priority; // e.g., 'medium'
        } else {
            // New task or redisplay after validation error
            $data['priority'] = post('priority', true);
        }
        
        $this->view('task_form', $data);
    }
    
    public function submit(): void {
        $this->validation->set_rules('priority', 'priority level', 'required');
        
        if ($this->validation->run() === true) {
            $data['task_title'] = post('task_title', true);
            $data['priority'] = post('priority', true); // Simple - no conversion needed
            
            $this->db->insert($data, 'tasks');
        }
    }
}

Flexible Checked Parameter

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

PHP
// All of these produce a checked radio button:
echo form_radio('option', 'yes', true);
echo form_radio('option', 'yes', 'true');
echo form_radio('option', 'yes', 'yes');
echo form_radio('option', 'yes', 'on');
echo form_radio('option', 'yes', '1');
echo form_radio('option', 'yes', 1);

// All of these produce an unchecked radio button:
echo form_radio('option', 'yes', false);
echo form_radio('option', 'yes', 'false');
echo form_radio('option', 'yes', 'no');
echo form_radio('option', 'yes', 'off');
echo form_radio('option', 'yes', '0');
echo form_radio('option', 'yes', 0);

Key Differences from Checkboxes

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

PHP
// Radio buttons - simple string values
$selected_value = post('priority', true); // Returns 'low', 'medium', 'high', or '' (if not set in POST data)

// Checkboxes - require conversion
$checkbox_value = (int) (bool) post('complete', true); // Returns 1 or 0

Simple Examples

Basic radio button (unchecked):

PHP
echo form_radio('color', 'red');
// Output: <input type="radio" name="color" value="red">

Checked radio button:

PHP
echo form_radio('color', 'blue', true);
// Output: <input type="radio" name="color" value="blue" checked="checked">

With comparison logic (common pattern):

PHP
$selected_color = 'blue';
echo form_radio('color', 'red', $selected_color === 'red');
echo form_radio('color', 'blue', $selected_color === 'blue');
echo form_radio('color', 'green', $selected_color === 'green');

Working with Radio Button Groups

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

PHP
// Define options
$status_options = [
    'pending' => 'Pending',
    'in_progress' => 'In Progress', 
    'completed' => 'Completed'
];

$selected_status = post('status', true) ?? 'pending';

foreach ($status_options as $value => $label) {
    echo '<div>';
    echo form_radio('status', $value, $selected_status === $value);
    echo ' ' . $label;
    echo '</div>';
}

Common Attributes

Add HTML attributes as needed:

PHP
$attributes = [
    'class' => 'form-radio',
    'id' => 'option-premium',
    'data-price' => '99.99'
];
echo form_radio('plan', 'premium', $selected_plan === 'premium', $attributes);

Form Submission Behavior

When a form with radio buttons submits:

PHP
// If a radio button is selected:
$value = post('priority', true); // Returns the selected value, e.g., 'high'

// If NO radio button is selected:
$value = post('priority', true); // Returns '' (empty string)

**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:

SQL
CREATE TABLE tasks (
    id INT PRIMARY KEY AUTO_INCREMENT,
    task_title VARCHAR(255),
    priority ENUM('low', 'medium', 'high') DEFAULT 'medium',
    status ENUM('pending', 'in_progress', 'completed') DEFAULT 'pending'
);

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.