Form processing

In the previous part, a simple form was created and displayed. However, nothing happened when the form was submitted.

To handle submission of a form, the form must be processed.

Processing the form

Open Application/Controllers/IndexController.php and modify the helloAction method to look like this:

public function helloAction() { $name = 'Unknown'; $form = new HelloForm(); if ($form->process($this->getRequest())) { $name = $form->NameField->getValue(); } $this->setViewItem('Title', 'Hello!'); return new View(['Name' => $name, 'Form' => $form]); }

Let's try it again.

Open the http://localhost/hello page, enter a name in the text field and click on the Say hello button:

Hello, Jane Doe


The process method

When the forms process method is invoked, all submitted form values will be processed and validated (more about validating later). It will return true if, and only if:

  1. The form was actually submitted.
  2. There was no validation failures.

In other words, if process returns true, the user has submitted valid input and the values from the form fields can be safely used or stored.

In our case, we use the value from the text field to create a personal greeting.

A common design pattern used with form submission is the Post/Redirect/Get pattern. To implement this, the redirect should occur when process returns true.

Validating the form

In many cases, the submitted values should probably be validated before they are used.

To demonstrate how form validation works, we will now make sure that the user can not enter "Foo Bar" as a name.

Open Application/Forms/HelloForm.php and add the onValidate method:

class HelloForm extends PostForm { public $NameField; public function __construct() { $this->NameField = new TextField('name'); } protected function onValidate(): void { if ($this->NameField->getValue() === 'Foo Bar') { $this->NameField->setError('That is not a real name'); } } }

Open the http://localhost/hello page, enter "Foo Bar" in the text field and click on the Say hello button:

Hello, Unknown

Well, it seems that the form was not processed (hint: the greeting message).

However, it would for sure be more user-friendly to display an error message on the screen.

Open Application/Views/Index/hello.twig and add the error label to the form:

<p> <label>Enter your name</label> {{ Model.Form.NameField | raw }} {% if Model.Form.NameField.Error %} <label class="error">{{ Model.Form.NameField.Error }}</label> {% endif %} </p>

...and try again:

That is not a real name

That's better!

This concluded a brief introduction to form handling.

In the next part, we will revisit our product list and create a basic API to retrieve it.

✎ Published in category get started