Trongate Website Homepage

Presenting Forms

In Trongate, presenting forms involves coordination between a controller file and a view file. This guide demonstrates how to display a form for creating or updating records, enabling you to create a form similar to the example below:

A basic form
Example of a basic form interface displayed within a webpage. This form includes fields for username, first name, last name, and email address, along with options to submit or cancel.

Template designs may vary, so your form might look different from the example shown above.

The Controller File

Let's pick up where we left off on the previous page. Create a file named 'Students.php' in the 'controllers' directory with the following code:

<?php
class Students extends Trongate {

    public function create(): void {

        $this->module('trongate_security');
        $this->trongate_security->_make_sure_allowed();

        $update_id = (int) segment(3);
        $submit = post('submit');

        if (($submit === '') && ($update_id>0)) {
            $data = $this->get_data_from_db($update_id);
        } else {
            $data = $this->get_data_from_post();
        }

        if ($update_id>0) {
            $data['headline'] = 'Update Student Record';
            $data['cancel_url'] = BASE_URL.'students/show/'.$update_id;
        } else {
            $data['headline'] = 'Create New Student Record';
            $data['cancel_url'] = BASE_URL.'students/manage';
        }

        $data['form_location'] = BASE_URL.'students/submit/'.$update_id;
        $data['view_file'] = 'create';
        $this->template('admin', $data);
    }

    private function get_data_from_db(int $update_id): ?array {
        $record_obj = $this->model->get_where($update_id, 'students');

        if ($record_obj === false) {
            $this->template('error_404');
            die();
        } else {
            $data = (array) $record_obj;
            return $data;        
        }
    }

    private function get_data_from_post(): array {
        return [
            'username' => post('username', true),
            'first_name' => post('first_name', true),
            'last_name' => post('last_name', true),
            'email_address' => post('email_address', true)
        ];
    }

}

If this seems complex, don't worry! Key parts of the code will be explained below.

The 'Create' Method

The create() method is responsible for displaying the form and handling initial form data.

Viewing The Form

In accordance with Trongate's automatic URL routing mechanism, the form can be accessed via a URL with the following structure:

https://example.com/students/create

Replace https://example.com with your base URL. Trongate routes URLs to modules and methods based on the following rules:

  • First Segment: Specifies the module and class. Here, 'students' maps to Students.php.
  • Second Segment: Specifies the method. 'create' maps to create().
  • Third Segment: An optional record ID can be provided for update scenarios.

Understanding The 'Create' Method

Let's break down each of the key parts of the create() method.

1. Security Check

We load the 'Trongate Security' module and invoke _make_sure_allowed() to ensure that only authorized users can access the form:

$this->module('trongate_security');
$this->trongate_security->_make_sure_allowed();

This step is optional. For more details on how Trongate handles user authorization, refer to the Authorization & Authentication chapter of our documentation.

2. Determine Form Purpose

We use Trongate's segment() method to check the URL for an update ID. This helps us determine whether the form is for creating a new record or updating an existing one:

$update_id = (int) segment(3);

3. Check If the Form Has Been Submitted

We determine if the form has been submitted by checking for the presence of the 'submit' button in the POST data using Trongate's post() function:

$submit = post('submit');

Checking if the form has been submitted helps us decide how to populate the form fields. If the 'submit' button is present, it indicates that the form has been submitted, allowing us to handle the data accordingly.

4. Populate Form Data

The `IF/ELSE` statement pre-populates the form data based on whether it is a create or update operation:

if (($submit === '') && ($update_id>0)) {
    $data = $this->get_data_from_db($update_id);
} else {
    $data = $this->get_data_from_post();
}

The get_data_from_post() method returns an array of posted form values. It will return empty strings for fields not present in the POST data, making it useful for initial form creation.

5. Set Form Metadata

We set the form headline, cancel URL, and form submission URL based on whether it is an update or create operation:

if ($update_id > 0) {
    $data['headline'] = 'Update Student Record';
    $data['cancel_url'] = BASE_URL . 'students/show/' . $update_id;
} else {
    $data['headline'] = 'Create New Student Record';
    $data['cancel_url'] = BASE_URL . 'students/manage';
}

$data['form_location'] = BASE_URL . 'students/submit/' . $update_id;

6. Load the View

Finally, we specify the view file to be loaded and render an HTML template using Trongate's template() method:

$data['view_file'] = 'create';
$this->template('admin', $data);

Trongate assumes view files are PHP files, so omit the .php suffix.

The View: Rendering the Form

Next, let’s focus on the view file.

Create a file named create.php in the 'views' sub-directory with the following code:

<h1 class="text-center"><?= $headline ?></h1>
<div class="container container-xs">
    <?php
    echo validation_errors();
    echo form_open($form_location);
    echo form_label('Username');
    echo form_input('username', $username, array("placeholder" => "Enter Username"));
    echo form_label('First Name');
    echo form_input('first_name', $first_name, array("placeholder" => "Enter First Name"));
    echo form_label('Last Name');
    echo form_input('last_name', $last_name, array("placeholder" => "Enter Last Name"));
    echo form_label('Email Address');
    echo form_email('email_address', $email_address, array("placeholder" => "Enter Email Address"));
    echo form_submit('submit', 'Submit');
    echo anchor($cancel_url, 'Cancel', array('class' => 'button alt'));
    echo form_close();
    ?>
</div>

Understanding the View File

Here’s a breakdown of the key components within the view file:

1. Display the Headline

The following code displays the page headline:

<h1 class="text-center"><?= $headline ?></h1>

The CSS class of 'text-center' is a rule that exists within Trongate CSS. It merely applies a text-align value of 'center' to the headline and does not play any role in the validation process.

For improved security and reliability, use Trongate's out() function. For example:

<h1><?= out($headline) ?></h1>

2. Show Validation Errors

The validation_errors() function is the used to display any validation errors that may have occurred during form submission.

echo validation_errors();

3. Render the Form

The following code renders the form using Trongate's helper functions:


echo form_open($form_location);
echo form_label('Username');
echo form_input('username', $username, array("placeholder" => "Enter Username"));
echo form_label('First Name');
echo form_input('first_name', $first_name, array("placeholder" => "Enter First Name"));
echo form_label('Last Name');
echo form_input('last_name', $last_name, array("placeholder" => "Enter Last Name"));
echo form_label('Email Address');
echo form_email('email_address', $email_address, array("placeholder" => "Enter Email Address"));
echo form_submit('submit', 'Submit');
echo anchor($cancel_url, 'Cancel', array('class' => 'button alt'));
echo form_close();

Helper functions used:

Function Description
validation_errors() Retrieves and displays validation error messages, if any exist.
form_open() Generates the opening tag for an HTML form.
form_label() Generates an HTML label element with optional attributes.
form_input() Creates a text input field with customizable attributes.
form_email() Generates an HTML input element with type "email".
form_submit() Creates a submit button to process the form.
anchor() Generates an HTML anchor (link) element.
form_close() Generates the closing tag for an HTML form, including a hidden CSRF token.

For more on Trongate's form helper functions, see the Form Helpers API Reference.

Final Thoughts

Keep in mind that the methodology described above is one of many possible approaches.

Next, we will explore how to set form validation rules. Read on!