Contact Form Example
The following can be used to construct a simple contact form using the view and action.
Template (views/contact-form.html)
<h1>Contact Us</h1>
<!--flush-->
<form method="post" action="/contact-form">
<!--csrf-->
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<button type="submit">Send</button>
</form>
Action Handler (actions/contact-form.php)
<?php
class ContactForm {
public function post() {
// Validate CSRF.
// If invalid it would print an error and stop the execution
verifyCsrf();
// Get form data
$name = getPost('name');
$email = getPost('email');
$message = getPost('message');
// Validate
if ($name && $email && $message) {
// Process (send email, save to DB, etc.)
// ... your code here ...
setFlash('success', 'Message sent!');
redirect('/contact-form');
}
// Display form again with error
setFlash('error', 'All fields required');
return ['name' => $name, 'email' => $email, 'message' => $message];
}
}