You will learn how you can use Kirby's API to create pages based on user input entered into a form on the frontend. A typical use case for this is an event or newsletter registration form.
Let's first have a look at the content structure: We have an
events page with the events stored as subpages and a
success page which we use later to display a success message.
First, we need the event registration form, which we will save in a snippet called
The form contains some form fields (
message) and a honeypot field to ensure a minimum level of spam bot protection.
The honeypot field needs to be positioned off the screen via CSS. Therefore add these styles to your stylesheet (you can change the class and styling).
When we submit the form, the
action attribute calls the URL of the current page. This allows us to process the input data in the
event.php controller. We will get to this in a bit.
The form snippet is included the
event.php template because we want to render it on every event page that uses this template.
The template renders the content of each event page. We want to add the registration form snippet below.
Additionally, we will display alerts if the user filled in the form incorrectly or the registration failed.
Since this is a lot of stuff, let's go through this one step at a time:
The form evaluation starts once we receive a
POST request. First, we check if a bot was trapped in our honeypot. If this is the case, we send him back to the page and stop script execution.
We then fetch the values of each form field from the
POST data into the
$data variable. We can use the
get() helper to do so:
Next, we check if all form fields have been filled according to our validation rules using the
All fields are required and must be filled out.
namefield is required.
We also want to tell the user what is wrong if the validation fails. We create an array of messages for each validated field:
To prevent garbage data, you may want to use validators on the other fields as well, for example by limiting input to a given character set (using regex patterns).
If all went well, we authenticate using the almighty
kirby user and try to create a new subpage within a
try/catch block, which allows us to react on possible errors. We store all registrations as subpages of the current
event page. If the registration was successfully created, two things happen:
- We store the current page URI and the name in the session.
- We redirect to the
If the registration fails, we add the error message to our alerts variable.
If the registration was successful, the user is redirected to the
text field, we include a placeholder for the event title to customize it a little. To actually display the title, we use a
kirbyTags:after hook in a plugin.
success page is rendered using the
In the plugin, we replace the
event placeholders in the text with the data we stored in the session.
For a working example, download the demo "Eventkit".