form_date()

function form_date(string $name, ?string $value = null, array $attributes = []): string

Description

Generates an HTML date input field with a native browser date picker. The input always submits dates in ISO 8601 format (YYYY-MM-DD), regardless of how the browser displays the date to the user.

Demonstration

Below is the native HTML5 date input rendered by form_date():

HTML5 Date Format: The value must always be in YYYY-MM-DD format. Browsers display dates according to the user's locale, but your PHP code always receives predictable ISO 8601 format.

Parameters

ParameterTypeDescriptionDefaultRequired
$name string The name attribute for the input element N/A Yes
$value string|null The date value in YYYY-MM-DD format null No
$attributes array Additional HTML attributes as key-value pairs [] No

Return Value

TypeDescription
stringThe generated HTML date input element

Understanding the Attributes Array

The $attributes array accepts standard HTML input attributes. For date inputs, these are particularly useful:

AttributeDescriptionExample Value
min Earliest selectable date (YYYY-MM-DD) '2025-01-01'
max Latest selectable date (YYYY-MM-DD) '2025-12-31'
required Field must have a value ['required' => true]
readonly Prevent user editing ['readonly' => true]
disabled Disable the input ['disabled' => true]

Boolean Attributes: Pass true for boolean attributes like required, readonly, or disabled. This generates clean HTML5 syntax: <input required>

Example #1: Basic Date Input

The example above shows the simplest usage. This generates a date input field where users can select any date using their browser's native date picker.

Example #2: Date Input with Pre-set Value

View file:

The example above demonstrates setting a default value. When creating new records, it's common to pre-fill date fields with today's date or another sensible default.

Form Repopulation: When a form fails validation, use post('field_name', true) in the controller to fetch the submitted value and pass it back to the view for repopulation.

Example #3: Date Input with Business Constraints

View file:

The example above shows how to enforce business rules using min and max attributes. The browser prevents users from selecting dates outside the allowed range.

Server-side Validation Required: Always validate date inputs server-side with the valid_date rule. Browser validation can be bypassed by malicious users.

Example #4: Complete Create/Update Workflow

View file:

The example above demonstrates the complete create/update pattern. Notice that segment(3, 'int') is properly type-cast, and the form works for both creating new records and editing existing ones.

Database Compatibility: MySQL's DATE type uses YYYY-MM-DD format, which matches HTML5 date inputs exactly. No date format conversion is needed between the form and database.