form_open()
function form_open(string $location, array $attributes = []): string
Description
Generates the opening tag for an HTML form. This is typically the first function called when building a form in Trongate.
Parameters
| Parameter | Type | Description |
|---|---|---|
| $location | string | The URL or path where the form will be submitted. |
| $attributes | array | (optional) HTML attributes for the form element. Defaults to an empty array ([]). |
Return Value
| Type | Description |
|---|---|
| string | The HTML opening tag for the form. |
Example #1: Basic Form
PHP
echo form_open('users/submit');
echo form_input('username', '');
echo form_submit('submit', 'Save');
echo form_close();
// Output:
// <form action="https://example.com/users/submit" method="post">
// <input type="text" name="username">
// <button type="submit" name="submit">Save</button>
// </form>Example #2: Form with GET Method
PHP
$attributes = [
'method' => 'get',
'id' => 'search-form'
];
echo form_open('products/search', $attributes);
// Output:
// <form action="https://example.com/products/search" method="get" id="search-form">Example #3: Form with Automatic Error Highlighting
PHP
$attributes = [
'class' => 'highlight-errors'
];
echo form_open('users/register', $attributes);
// Output:
// <form action="https://example.com/users/register" method="post" class="highlight-errors">Example #4: Trongate MX Form
PHP
$attributes = [
'mx-post' => 'comments/create',
'mx-target' => '#comment-list',
'mx-swap' => 'beforeend'
];
echo form_open('#', $attributes);
// Output:
// <form mx-post="comments/create" mx-target="#comment-list" mx-swap="beforeend" action="#" method="post">Regarding Trongate MX: When using MX attributes like mx-post, the form submits asynchronously without page reloads. The mx-post attribute takes precedence over the action attribute.
Additional guidance on how to work with Trongate MX is available from the Trongate MX Documentation.
URL Handling
The $location parameter supports different URL formats:
PHP
// Relative path (prepended with BASE_URL)
echo form_open('products/create');
// Output: <form action="https://example.com/products/create" method="post">
// Absolute path
echo form_open('/admin/users');
// Output: <form action="/admin/users" method="post">
// Full URL
echo form_open('https://api.example.com/submit');
// Output: <form action="https://api.example.com/submit" method="post">- Always pair
form_open()withform_close()to ensure proper form structure and CSRF protection. - The default method is
post. Specify['method' => 'get']for GET forms. - For file uploads, use
form_open_upload()instead ofform_open(). - Relative paths are automatically converted to full URLs using the
BASE_URLconstant. - All attributes are automatically HTML-escaped for security.
- The
methodattribute is handled specially - it's extracted from the attributes array and placed in the proper position.