### Quick Example: HTML Template for Kirby Uniform
Source: https://github.com/mzur/kirby-uniform/blob/master/README.md
This HTML template illustrates how to integrate Kirby Uniform forms into your website. It includes input fields, CSRF and honeypot protection, submission handling, and displays success or error messages. Requires a Kirby environment with the Uniform plugin installed.
```html+php
success()): ?>
Success!
$form]); ?>
```
--------------------------------
### Install Kirby Form using Composer (Bash)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-form/README.md
Provides the Composer commands to install the Kirby Form library for different Kirby versions. This is a prerequisite for using the library in a Kirby project.
```bash
# Kirby 2
composer require mzur/kirby-form:^1.0
# Kirby 3
composer require mzur/kirby-form:^2.0
```
--------------------------------
### Install Kirby Flash (Bash)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-flash/README.md
Commands to install the Kirby Flash library using Composer. It specifies different versions for Kirby v2 and Kirby v3.
```bash
# Kirby v2
composer require mzur/kirby-flash:^1.0
# Kirby v3
composer require mzur/kirby-flash:^2.0
```
--------------------------------
### Multiple Guards and Actions Chaining in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/usage.md
Illustrates the chaining of multiple guards and actions in PHP. This allows for a sequence of spam checks and subsequent processing. The example chains a honeypotGuard, a calcGuard, and an emailAction.
```php
if (kirby()->request()->is('POST')) {
$form->honeypotGuard()
->calcGuard()
->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
]);
}
```
--------------------------------
### Chaining Guards and Actions in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/usage.md
Demonstrates how to chain multiple guards and actions in PHP for form processing. Guards are executed before actions, providing spam protection. Actions handle the form submission logic. This example shows a CalcGuard followed by an emailAction.
```php
if (kirby()->request()->is('POST')) {
$form->calcGuard(['field' => 'result'])
->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
]);
}
```
--------------------------------
### Quick Example: PHP Controller for Kirby Uniform
Source: https://github.com/mzur/kirby-uniform/blob/master/README.md
This PHP code demonstrates how to set up a controller for the Kirby Uniform plugin. It defines form fields with validation rules and uses the emailAction to send form data. Requires the Uniform plugin and Kirby framework.
```php
[
'rules' => ['required', 'email'],
'message' => 'Email is required',
],
'message' => [],
]);
if ($kirby->request()->is('POST')) {
$form->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
])->done();
}
return compact('form');
};
```
--------------------------------
### Chaining Multiple Actions in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/usage.md
Demonstrates chaining multiple actions in PHP for form submission. This allows for sequential execution of different tasks like sending emails and logging. Note that if one action fails, subsequent actions will not be executed. The example chains two `emailAction` calls and a `logAction`.
```php
if (kirby()->request()->is('POST')) {
$form->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
])
->emailAction([
'to' => 'you@example.com',
'from' => 'info@example.com',
])
->logAction([
'file' => kirby()->roots()->site().'/messages.log'
]);
}
```
--------------------------------
### Controller Request Handling (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/upgrade-guide-v3-v4.md
Demonstrates how to access request information in Uniform v4 controllers using Kirby 3's request method, replacing the deprecated r::is() from Uniform v3/Kirby 2.
```php
request()->is('POST')) {
// run actions
}
return compact('form');
};
```
--------------------------------
### Creating a Custom Uniform Action in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/actions.md
Provides an example of creating a custom action class in PHP for Uniform. The custom action extends the base `Action` class and implements the `perform` method to process form data. It demonstrates how to access form data and handle potential exceptions.
```php
form->data());
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
}
}
```
--------------------------------
### Configure POST Route for Contact Form - PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/ajax.md
Sets up a route to handle POST requests on '/contact'. It defines validation rules for email and message fields using Kirby Uniform, preventing default flashing and redirection. Returns JSON errors on validation failure or success.
```php
[
'pattern' => 'contact',
'method' => 'POST',
'action' => function () {
$form = new \Uniform\Form([
'email' => [
'rules' => ['required', 'email'],
'message' => 'Please enter a valid email address',
],
'name' => [],
'message' => [
'rules' => ['required'],
'message' => 'Please enter a message',
],
]);
// Perform validation and execute guards.
$form->withoutFlashing()
->withoutRedirect()
->guard();
if (!$form->success()) {
// Return validation errors.
return Response::json($form->errors(), 400);
}
// If validation and guards passed, execute the action.
$form->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
]);
if (!$form->success()) {
// This should not happen and is our fault.
return Response::json($form->errors(), 500);
}
// Return code 200 on success.
return Response::json([], 200);
}
]
```
--------------------------------
### Chain Multiple Uniform Actions in Sequence (PHP)
Source: https://context7.com/mzur/kirby-uniform/llms.txt
Execute a series of actions sequentially for a Uniform form, ensuring shared validation across all steps. This example demonstrates chaining the Calculation Guard, file upload, logging, email notification, and webhook actions. Actions are executed in the order they are called, and if any action fails, subsequent actions are skipped. Form data and errors are flashed to the session.
```php
['rules' => ['required', 'min:2']],
'email' => ['rules' => ['required', 'email']],
'resume' => ['rules' => ['required', 'file', 'maxSize:3000000']],
]);
if ($kirby->request()->is('POST')) {
$form
->calcGuard() // Add calculation captcha
->uploadAction([
'fields' => [
'resume' => [
'target' => kirby()->root('content') . '/resumes',
],
],
])
->logAction([
'file' => kirby()->root('logs') . '/applications.log',
])
->emailAction([
'to' => 'hr@example.com',
'from' => 'careers@example.com',
'subject' => 'New application from {name}',
])
->webhookAction([
'url' => 'https://api.example.com/applications',
'json' => true,
])
->done(); // Execute all actions and redirect
}
// All actions execute in order
// If any action fails, subsequent actions are skipped
// Form data and errors are flashed to session
```
--------------------------------
### Accessing Form Data with Kirby's get() Helper (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/answers.md
Illustrates how to access submitted form data from anywhere in your Kirby application using the `get()` helper function. This is useful when you need to work with field values outside of direct Uniform snippet processing. It assumes a field named 'myfield'.
```php
get('myfield')
```
--------------------------------
### HTML+PHP Form Template with Validation Feedback and Honeypot
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/basic.md
This HTML+PHP template renders a form with input fields for email, name, and message. It dynamically applies an 'error' class to fields with validation errors and displays old input values. It includes CSRF protection, honeypot spam fields, and conditional messages for form submission success or errors using the `uniform/errors` snippet.
```html+php
title()->html() ?>
success()): ?>
Thank you for your message. We will get back to you soon!
$form]) ?>
```
--------------------------------
### Email Subject Templating (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/upgrade-guide-v3-v4.md
Shows the change in string templating for email subjects in Uniform v4/Kirby 3, using {{ }} instead of { } for variables. Variables with no replacement are now removed.
```php
$form->emailAction([
// ...
'subject' => 'New request from {{firstname}} {{lastname}}',
]);
```
--------------------------------
### PHP Form Controller Logic with Validation and Email Action
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/basic.md
This PHP controller sets up a Uniform form with validation rules for email and message fields. It handles POST requests to send form data via email to a specified recipient, utilizing the `emailAction` and `done` methods. It also manages form state for displaying old input and success messages.
```php
[
'rules' => ['required', 'email'],
'message' => 'Please enter a valid email address',
],
'name' => [],
'message' => [
'rules' => ['required'],
'message' => 'Please enter a message',
],
]);
if ($kirby->request()->is('POST')) {
$form->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
])->done();
}
return compact('form');
};
```
--------------------------------
### Create Contact Form with Validation Fields - HTML+PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/ajax.md
Renders a contact form with fields for email, name, and message. It includes server-side logic to dynamically set the form action URL and CSRF/honeypot fields. Basic CSS is included for styling and error indication.
```html+php
title()->html() ?>
```
--------------------------------
### JSON Log Entry Format with Uniform Template
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/log.md
This example shows the JSON format for log entries when using the `uniform/log-json` template. It includes fields like timestamp, IP address, user agent, and the submitted form data, useful for structured logging.
```json
{"timestamp":"2016-12-20T09:16:18+00:00","ip":"127.0.0.1","userAgent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/51.0","email":"joe@user.com","message":"This is a test submission."}
```
--------------------------------
### Get Current Session Key (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-flash/README.md
Shows how to retrieve the currently configured session key that the Flash library uses for storing its data.
```php
Jevets\Kirby\Flash::sessionKey();
```
--------------------------------
### Managing Multiple Forms with Unique Session Storage (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/answers.md
This example shows how to prevent error message conflicts between multiple forms on the same page by assigning each form a unique session storage key. It initializes two `Form` instances, 'contact-form' and 'newsletter-form', with distinct identifiers.
```php
request()->is('POST')) {
if (/* contact form sent */) {
$contactForm->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
]);
} elseif (/* newsletter form sent */) {
$newsletterForm->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
]);
}
}
return compact('form');
};
```
--------------------------------
### Custom Email Body with Form Data (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/email.md
This PHP example illustrates creating a custom email body using template syntax. It allows embedding form field values like 'name' into a personalized greeting, making the email more user-friendly.
```php
'body' => 'Dear {{name}}, we will get back to you soon!',
```
--------------------------------
### Email Confirmation Message Template
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/extended.md
This is a simple template file used for sending a success email confirmation. It dynamically includes the user's name, booth size, number of attendees, and whether they subscribed to the newsletter. This template is likely used by an action within the Kirby Uniform plugin. It expects variables like `$name`, `$booth`, `$attendees`, and `$newsletter` to be passed to it.
```html+php
Dear ,
thank you for the registration of a booth with attendees and your subscription to our newsletter!
```
--------------------------------
### Process Form with Email and Log Actions - PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/extended.md
This PHP code snippet defines a Kirby controller to handle form submissions. It utilizes the Uniform library to validate fields like name, email, attendees, booth, and newsletter. Upon successful validation, it triggers multiple actions: sending an email to the site owner, logging the submission to a file, and sending a confirmation email to the submitter. If any validation fails, error messages are associated with the respective fields. Finally, it redirects the user to a success page.
```php
[
'rules' => ['required'],
'message' => 'Please enter your name',
],
'email' => [
'rules' => ['required', 'email'],
'message' => 'Please enter a valid email address',
],
'attendees' => [
'rules' => ['required', 'num'],
'message' => 'Please enter a number of attendees',
],
'booth' => [
'rules' => ['required', 'in' => [['6 sqm', '12 sqm', 'special']]],
'message' => 'Please choose a booth size',
],
'newsletter' => [
'rules' => ['in' => [['yes', 'no']]],
'message' => "Please choose 'yes' or 'no'",
],
'message' => [],
]);
if ($kirby->request()->is('POST')) {
$form->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
// Dynamically generate the subject with a template.
'subject' => 'New registration for a {{booth}} booth',
])
->logAction([
'file' => $kirby->roots()->site().'/registrations.log',
])
->emailAction([
// Send the success email to the email address of the submitter.
'to' => $form->data('email'),
'from' => 'info@example.com',
// Set replyTo manually, else it would be set to the value of 'email'.
'replyTo' => 'me@example.com',
'subject' => 'Thank you for your registration!',
// Use a template for the email body (see below).
'template' => 'success',
]); // No done() here because we do a custom redirect below.
if ($form->success()) {
go(page('registration/success')->url());
}
}
return compact('form');
};
```
--------------------------------
### Render Form Fields and Display Errors in HTML+PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/extended.md
This snippet shows how to render a form in HTML+PHP using the Kirby Uniform plugin. It includes labels, input fields (text, email, number, select, radio), textareas, and CSRF/honeypot protection. It dynamically adds 'error' classes to fields with validation issues and uses a snippet to display error messages. Dependencies include the Kirby CMS and the Uniform plugin.
```html+php
title()->html() ?>
```
--------------------------------
### Handle Form Submission and Validation with JavaScript
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/ajax.md
An event listener waits for the page to load, then attaches a submit handler to the form. It uses XMLHttpRequest to send form data via POST. On response, it displays success messages or renders validation errors by adding an 'error' class to invalid fields.
```js
window.addEventListener('load', function () {
var form = document.querySelector('form');
var message = document.getElementById('message');
var fields = {};
form.querySelectorAll('[name]').forEach(function (field) {
fields[field.name] = field;
});
// Displays all error messages and adds 'error' classes to the form fields with
// failed validation.
var handleError = function (response) {
var errors = [];
for (var key in response) {
if (!response.hasOwnProperty(key)) continue;
if (fields.hasOwnProperty(key)) fields[key].classList.add('error');
Array.prototype.push.apply(errors, response[key]);
}
message.innerHTML = errors.join(' ');
}
var onload = function (e) {
if (e.target.status === 200) {
message.innerHTML = 'Success!'
} else {
handleError(JSON.parse(e.target.response));
}
};
var submit = function (e) {
e.preventDefault();
var request = new XMLHttpRequest();
request.open('POST', e.target.action);
request.onload = onload;
request.send(new FormData(e.target));
// Remove all 'error' classes of a possible previously failed validation.
for (var key in fields) {
if (!fields.hasOwnProperty(key)) continue;
fields[key].classList.remove('error');
}
};
form.addEventListener('submit', submit);
});
```
--------------------------------
### CSS Setup for Kirby Uniform Honeypot
Source: https://github.com/mzur/kirby-uniform/blob/master/README.md
This CSS snippet is used to hide the honeypot field in Kirby Uniform forms. It positions the element off-screen to prevent it from being visible to users while still being detectable by bots. This is a standard setup for honeypot fields.
```css
.uniform__potty {
position: absolute;
left: -9999px;
}
```
--------------------------------
### Kirby Uniform Form Initialization and Basic Usage (PHP)
Source: https://context7.com/mzur/kirby-uniform/llms.txt
Demonstrates how to initialize a Kirby Uniform form with validation rules and set up a basic email action. It covers defining field rules and messages, handling POST requests, and performing the email action. This snippet is intended for use within a Kirby controller.
```php
[
'rules' => ['required', 'min:3'],
'message' => 'Name must be at least 3 characters',
],
'email' => [
'rules' => ['required', 'email'],
'message' => 'Valid email is required',
],
'message' => [
'rules' => ['required', 'minLength:10'],
'message' => 'Message must be at least 10 characters',
],
]);
if ($kirby->request()->is('POST')) {
// Automatically validates, checks honeypot guard, sends email, and redirects
$form->emailAction([
'to' => 'contact@example.com',
'from' => 'noreply@example.com',
'subject' => 'Contact Form Submission',
])->done();
}
return compact('form');
};
```
--------------------------------
### Using Uniform Action Magic Methods in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/actions.md
Illustrates the use of magic methods to instantiate and attach actions to a Uniform Form instance in PHP. This provides a more concise syntax compared to manually creating action objects.
```php
use Uniform\Form;
use Uniform\Actions\EmailAction;
$form = new Form;
if (kirby()->request()->is('POST')) {
$action = new EmailAction($form, [/* options */]);
$form->action($action);
}
```
```php
use Uniform\Form;
use Uniform\Actions\EmailAction;
$form = new Form;
if (kirby()->request()->is('POST')) {
$form->action(EmailAction::class, [/* options */]);
}
```
--------------------------------
### Get Old Form Data - HTML+PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/methods.md
Retrieves previously submitted form data that was flashed to the session. This is useful for repopulating form fields after validation errors. Note that this method may not work for file upload fields.
```html+php
```
--------------------------------
### Using Multiple Guards in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/guards/guards.md
Demonstrates how to chain multiple guards, such as HoneypotGuard and CalcGuard, within a Uniform form instance. This allows for layered spam protection. The code assumes a POST request and initializes the Form object.
```php
use Uniform\Form;
$form = new Form;
if (kirby()->request()->is('POST')) {
$form->honeypotGuard([/* options */])
->calcGuard([/* options */])
// more guards or call actions
}
```
--------------------------------
### Alternative Guard Instantiation in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/guards/guards.md
Demonstrates an alternative way to register a guard with Uniform without using magic methods. This involves explicitly creating an instance of the guard class or passing the class name and options directly to the `$form->guard()` method. This approach offers more control but is less concise.
```php
use Uniform\Form;
use Uniform\Guards\CalcGuard;
$form = new Form;
if (kirby()->request()->is('POST')) {
$guard = new CalcGuard($form, [/* options */]);
$form->guard($guard);
}
// or
$form->guard(CalcGuard::class, [/* options */]);
```
--------------------------------
### Generating CSRF Token for AJAX (PHP Route)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/answers.md
Defines a GET route named 'gettoken' in the Kirby config that returns a JSON response containing a CSRF token. This is used in conjunction with JavaScript to refresh the token for AJAX form submissions on cached pages.
```php
[
'pattern' => 'gettoken',
'method' => 'GET',
'action' => function() {
return Response::json(['token' => csrf()]);
},
]
```
--------------------------------
### Initialize Uniform Form in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/usage.md
Demonstrates how to instantiate the Uniform Form class in a PHP controller. It includes setting up validation rules for fields like 'email' and 'message', and handling POST requests with an email action. Dependencies include the Uniform\Form class.
```php
[
'rules' => ['required', 'email'],
'message' => 'Please enter a valid email address',
],
'message' => [
'rules' => ['required'],
'message' => 'Please enter a message',
],
]);
if ($kirby->request()->is('POST')) {
$form->emailAction([
'to' => 'me@example.com',
'from' => 'info@example.com',
])->done();
}
return compact('form');
};
```
--------------------------------
### Configure Honeypot Field Name (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/guards/honeypot.md
This PHP code configures the honeypot guard to use a different name for the honeypot field. By default, the field is named 'website'. This example changes it to 'url'. This configuration is typically done within a controller.
```php
$form->honeypotGuard(['field' => 'url']);
```
--------------------------------
### Email Template Variable Access (HTML+PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/upgrade-guide-v3-v4.md
Illustrates how to access form field variables directly in Uniform v4/Kirby 3 email templates using shorthand echo syntax, compared to the older $data array access in Uniform v3/Kirby 2.
```html+php
This is a message from = $firstname ?> = $lastname ?>.
```
--------------------------------
### Initialize Honeytime Guard in Controller (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/guards/honeytime.md
Initializes the Honeytime Guard in a controller, providing the necessary encryption key. This activates the bot detection mechanism for the form. The `key` option is required for this configuration.
```php
$form->honeytimeGuard([
'key' => c::get('uniform.honeytime.key'),
]);
```
--------------------------------
### Set Flash Data with Keys and Arrays (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-flash/README.md
Demonstrates setting various types of flash data using the `flash()` function. This includes simple key-value pairs and arrays for multiple messages, often used for error reporting.
```php
flash('key', 'value');
flash('messages.success', ['Thanks for your feedback!']);
flash('messages.errors', ['Email is a required field']);
flash('username', 'jimihendrix');
```
--------------------------------
### Configure and Log Form Data in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/log.md
This PHP code snippet demonstrates how to set up form validation rules and then use the `logAction` method to append form data and submitter information to a log file. It requires the Uniform/Form library and handles POST requests.
```php
[
'rules' => ['required', 'email'],
'message' => 'Email is required',
],
'message' => [
'rules' => ['required'],
'message' => 'Message is required',
],
]);
if ($kirby->request()->is('POST')) {
$form->logAction([
'file' => kirby()->roots()->site().'/messages.log',
]);
}
return compact('form');
};
```
--------------------------------
### Chaining Built-in Uniform Actions in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/actions.md
Demonstrates how to chain multiple built-in actions (email, log, webhook) using the Uniform Form instance in PHP. Actions are executed sequentially and only if the form data passes validation and guards. If an action fails, subsequent actions are not executed.
```php
use Uniform\Form;
$form = new Form;
if (kirby()->request()->is('POST')) {
$form->emailAction([/* options */])
->logAction([/* options */])
->webhookAction([/* options */]);
}
```
--------------------------------
### Configure Form Fields and Exclusion in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/usage.md
Illustrates how to configure Uniform form fields. It shows how to define fields to be used and validated, how to exclude fields from validation by providing an empty rules array, and how to prevent certain fields from being flashed on validation errors using the 'flash' option. This is done during the Uniform\Form instantiation.
```php
$form = new Form([
'email' => [
'rules' => ['required', 'email'],
'message' => 'Please enter a valid email address',
],
'message' => [
'rules' => ['required'],
'message' => 'Please enter a message',
],
'name' => [], // Excluded from validation
]);
```
```php
$form = new Form([
'username' => [
'rules' => ['required'],
'message' => 'Please enter your username',
],
'password' => [
'rules' => ['required'],
'message' => 'Please enter a password',
'flash' => false, // Excluded from flashing
],
]);
```
--------------------------------
### Refactor sendform() to uniform() Call in PHP
Source: https://github.com/mzur/kirby-uniform/wiki/Upgrade-guide
Demonstrates the transformation of an old `sendform()` function call to the new `uniform()` function call in PHP. This change reflects the plugin's updated architecture, moving email-specific configurations into an 'actions' array and requiring explicit declaration of the `_from` field.
```php
$form = sendform(
'registration-form',
'me@example.com',
array(
'subject' => 'Exhibition - New registration',
'required' => array(
'name' => ''
),
'validate' => array(
'attendees' => 'num'
),
'snippet' => 'sendform-table',
'copy' => array(
'me-too@example.com'
)
)
);
```
```php
$form = uniform(
'registration-form',
array(
'required' => array(
'name' => '',
'_from' => 'email'
),
'validate' => array(
'attendees' => 'num'
),
'actions' => array(
array(
'_action' => 'email',
'to' => 'me@example.com',
'sender' => 'info@my-domain.tld',
'subject' => 'Exhibition - New registration',
'snippet' => 'uniform-email-table'
),
array(
'_action' => 'email',
'to' => 'me-too@example.com',
'sender' => 'info@my-domain.tld',
'subject' => 'Exhibition - New registration',
'snippet' => 'uniform-email-table'
)
)
)
);
```
--------------------------------
### Configure Validators with Arguments in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/usage.md
Demonstrates how to pass arguments to validators when defining rules for a Uniform\Form. This allows for complex validation scenarios like checking password length or if a value falls within a specific range. Arguments are provided as key-value pairs within the 'rules' array or as values in an associative array for 'between'.
```php
$form = new Form([
'password' => [
'rules' => ['required', 'min' => 8],
'message' => ['Please enter a password', 'The password must contain at least eight characters'],
],
'role' => [
'rules' => ['required', 'in' => [['manager', 'editor', 'admin']]],
'message' => ['Please choose a role', 'Invalid role'],
],
'salary' => [
'rules' => ['between' => [70000, 5000000]],
'message' => 'Please choose an adequate salary',
],
]);
```
--------------------------------
### Display Form Field Validation Errors in HTML+PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/examples/extended.md
This snippet defines a reusable form error display component for the Kirby Uniform plugin. It checks if there are any errors for a given field and, if so, displays them within a paragraph with the 'error-text' class. This helps to keep the main form template clean by abstracting error display logic. It depends on the `$form` and `$field` variables being available in the scope.
```html+php
error($field)): ?>
', $form->error($field)) ?>
```
--------------------------------
### Flash Helper Function Usage (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-flash/README.md
Explains the basic usage of the global `flash()` helper function. It covers calling it with one parameter to retrieve data and with two parameters to set data, including overwriting existing values.
```php
flash('my_key');
flash('my_other_key', 'Some Value');
flash('my_other_key', 'Some Other Value');
flash('my_other_key'); // "Some Other Value"
```
--------------------------------
### Registering a Custom Uniform Action in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/actions.md
Shows how to register a custom Uniform action class in PHP, making it available for use. This is typically done within a Kirby plugin's `index.php` file or via Composer's autoloader if the action is part of a package.
```php
'MyCustomAction.php'
], __DIR__);
```
--------------------------------
### Initialize and Validate Kirby Form (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-form/README.md
Demonstrates the basic initialization of the Kirby Form helper with validation rules and checks if the form submission is valid. It takes an array of field configurations and returns a boolean indicating validation success.
```php
$form = new Form([
'name' => [
'rules' => ['required'],
'message' => ['Name is required']
],
'phone' => [],
]);
if ($form->validates()) {
// Validation passed
// Do something with the data
}
```
--------------------------------
### Login Action - PHP
Source: https://context7.com/mzur/kirby-uniform/llms.txt
Authenticates users via form submission using their username and password. It requires 'username' and 'password' fields in the form and handles both successful logins and authentication failures, displaying an error message for the latter. The action is intended to be used with a POST request.
```php
['rules' => ['required']],
'password' => ['rules' => ['required']],
]);
if ($kirby->request()->is('POST')) {
$form->loginAction([
'user-field' => 'username', // Form field for username (default: 'username')
'password-field' => 'password', // Form field for password (default: 'password')
])->done();
}
// On success, user is logged in and redirected
// On failure, error message is displayed: "Wrong username or password."
// Template:
//
// $form]); ?>
```
--------------------------------
### Custom Guard Implementation in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/guards/guards.md
Provides a basic structure for creating a custom guard class in PHP for Uniform. It extends the base Guard class and implements the 'perform' method to define custom spam check logic. The class must be in the 'Uniform\Guards' namespace and optionally end with 'Guard' to use magic methods.
```php
reject();
}
}
}
```
--------------------------------
### Retrieve Flash Data (PHP)
Source: https://github.com/mzur/kirby-uniform/blob/master/vendor/mzur/kirby-flash/README.md
Shows how to retrieve flash data using the `flash()` function with just a key. It demonstrates retrieving a simple value, an array of messages, and a string value.
```php
$value = flash('key');
$success_messages = flash('messages.success'); // Array( 0 => 'Thanks for your feedback!' )
$username = flash('username'); // "jimihendrix"
```
--------------------------------
### Kirby Uniform Email Action Configuration (PHP)
Source: https://context7.com/mzur/kirby-uniform/llms.txt
Shows how to configure the email action for Kirby Uniform forms, including specifying recipients, sender, subject, reply-to address, and custom email templates. It also demonstrates how to enable sending a copy to the user and control HTML escaping. This snippet is useful for customizing email notifications from form submissions.
```php
['rules' => ['required', 'email']],
'subject' => ['rules' => ['required']],
'message' => ['rules' => ['required']],
'receive_copy' => [], // Optional checkbox field
]);
if ($kirby->request()->is('POST')) {
$form->emailAction([
'to' => 'admin@example.com',
'from' => 'system@example.com',
'replyTo' => $form->data('email'), // Reply to the sender
'subject' => 'Contact: {subject}', // Template string using form data
'receive-copy' => true, // Enable sending copy to user
'template' => 'emails/uniform-table', // Use custom email template
'escapeHtml' => true, // Escape HTML in form data (default: true)
])->done();
}
// Access old values in template for repopulation
//
// Check success status
// success()): ?>
//
Thank you! Your message was sent.
//
```
--------------------------------
### Registering Custom Guard in PHP
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/guards/guards.md
Illustrates how to register a custom guard class with Kirby so it can be automatically loaded. This snippet is typically placed in an `index.php` file within a Kirby plugin. It uses the `load` function to map the guard class.
```php
'MyCustomGuard.php'
], __DIR__);
```
--------------------------------
### PHP Login Action Controller for Kirby Uniform
Source: https://github.com/mzur/kirby-uniform/blob/master/docs/actions/login.md
This PHP code defines the controller logic for a login action using Kirby Uniform. It sets up validation rules for username and password, disables guards, and initiates the login process. It handles form submission, checks for success, and returns form data for template rendering. Dependencies include the Uniform\Form class and Kirby's request methods.
```php
[
'rules' => ['required'],
'message' => 'Please enter your username',
],
'password' => [
'rules' => ['required', 'min' => 8],
'message' => 'Please enter your password',
],
]);
if ($kirby->request()->is('POST')) {
$form->withoutGuards()
->loginAction();
if ($form->success()) {
// redirect to internal page
}
}
return compact('form');
};
```
--------------------------------
### Implement Time-Based Spam Protection (Honeytime Guard) (PHP)
Source: https://context7.com/mzur/kirby-uniform/llms.txt
Add time-based spam protection to Uniform forms by rejecting submissions that occur too quickly. This guard requires a unique encryption key configured in Kirby's options. It embeds an encrypted timestamp in a hidden field and rejects submissions if the time difference between form load and submission is less than a specified duration. The default minimum submission time is 10 seconds.
```php
base64_encode(random_bytes(16))
$form = new Form([
'email' => ['rules' => ['required', 'email']],
'message' => ['rules' => ['required']],
]);
if ($kirby->request()->is('POST')) {
$form->honeytimeGuard([
'key' => kirby()->option('uniform.honeytime.key'), // Required
'field' => 'uniform-honeytime', // Field name (default)
'seconds' => 5, // Minimum seconds before submission (default: 10)
])->emailAction([
'to' => 'info@example.com',
'from' => 'noreply@example.com',
])->done();
}
// Template:
//
// Encrypted timestamp is embedded in hidden field
// If form submitted < 5 seconds after load, rejected with:
// "The form was submitted too quickly and triggered spam protection."
```