form_close()

function form_close(): string

Description

Closes an HTML form. Always use this function instead of manually writing </form>. It automatically adds a CSRF token for security and handles validation error highlighting.

Parameters

This function does not accept any parameters.

Return Value

Type Description
string The closing </form> tag with hidden CSRF token and optional error highlighting JavaScript.

Example Usage

Imagine that you're building a simple task manager application, within a module named 'tasks'.

Your controller file, Tasks.php could have a method named create() which gets invoked when a user wishes to create a new task.

Inside the Tasks module, your create.php view file could have the following code:

This generates:

The code samples above are for demonstration purposes only. In a real-use case, you'd almost certainly need to add additional features such as security, pre-population of form fields, the ability to edit existing records and more.

How It Works

  1. When you call form_close(), it adds a hidden CSRF token to your form
  2. When the form is submitted, the Validation::run() method checks this token automatically
  3. If the token is missing or invalid, the submission is rejected

In the Tasks controller:

Automatic Error Highlighting

In addition to CSRF protection, form_close() also handles automatic validation error highlighting when used with forms that have the highlight-errors class.

When validation errors exist in the session, form_close() automatically:

  1. Injects errors as JavaScript (window.trongateValidationErrors)
  2. Injects highlighting script that adds the form-field-validation-error class to fields with errors
  3. Clears validation errors from the session

Example form with error highlighting:

The error highlighting feature works automatically when forms have the highlight-errors class. Default styling is provided in trongate.css. For more details, see the Displaying Validation Errors documentation.

Important Notes

  • Always use form_close() to close forms opened with form_open()
  • GET forms (like search forms) don't need CSRF protection - but you should still use form_close() for consistency
  • The CSRF token is validated automatically by $this->validation->run()
  • When validation errors exist in the session, form_close() injects error highlighting JavaScript and clears the errors
  • Error highlighting only works when the form has the highlight-errors class

Best Practice Pattern

Follow this simple pattern in your views: