Form handling is always a bit of a pain. In this recipe we will take you step by step through a basic example which you can then extend according to your needs.
This example consists of several parts and files:
- a contact page
- a template with the form
- a controller with the form logic, handling all the "heavy lifting"
- a plain text and an HTML email snippet
Create a contact page with a
contact.txt content file. For our means, we only need a title in the content files, the rest is up to you. You could, for example, store an introductory text or some variables – like the recipient email address.
For use in the Panel, you can also create a blueprint for the page. We will skip this step here.
contact.php template contains the form and will display error messages if something goes wrong or a success message if the form was successfully sent.
The form is displayed by default and hidden once the email was successfully sent. We also included a honeypot field to ensure a minimum level of spam bot protection.
The honeypot field needs to be positioned off the screen, so we need some styles for it. Add this to your stylesheet (you can also change the class and styling, of course).
$alert variables get controlled by user input, it is important to escape the text to protect against XSS vulnerabilities.
In our controller, the form evaluation starts once we receive a
POST request. First, we check if a bot was stupid enough to get trapped in our honeypot. In this case, we send him back to the page and stop script execution.
Next, we check if all form fields have been filled in according to our validation rules using the
- All fields are required and must be filled out.
namefield must be at least 3 characters long.
textfield must be between 3 and 3000 characters.
If all went well, we try to send the email in a
try - catch block. If that was also successful, we display a success message.
$kirby->email() method above, we have defined a template we want to use to send the email. In this example, we use a template called
We can use both, a plain text template and an HTML version. You can read more about this in the email guide.
Here are the two email templates:
The plain text template gets the extension
The HTML template gets the extension
Both templates are very simple. Kirby provides the variables we defined in the
data array ready to be used in the email templates as
Now you should have a working contact form you can experiment with.
Some ideas for extending this basic example:
- Implement some sort of captcha for better spam protection.
- Integrate other field types.
- Send files as attachments.
- Create pages from form data instead of or in addition to sending email.