Form-create Tag
Statamic forms serve to collect, report, and reuse user submitted data. This tag handles the HTML markup, redirect behavior, and success/error states and messages for these forms.
Overview#
Here we'll be creating a form to submit an entry in a contact form.
{{ form:create in="contact" }}
{{ if errors }}
<div class="bg-red-300 text-white p-2">
{{ errors }}
{{ value }}<br>
{{ /errors }}
</div>
{{ /if }}
{{ if success }}
<div class="bg-green-300 text-white p-2">
{{ success }}
</div>
{{ /if }}
{{ fields }}
<div class="p-2">
<label>{{ display }}</label>
<div class="p-1">{{ field }}</div>
{{ if error }}
<p class="text-gray-500">{{ error }}</p>
{{ /if }}
</div>
{{ /fields }}
<button>{{ form_button_label }}</button>
{{ /form:create }}
<s:form:create in="contact">
@if (count($errors) > 0)
<div class="bg-red-300 text-white p-2">
@foreach ($errors as $error)
{{ $error }}<br>
@endforeach
</div>
@endif
@if ($success)
<div class="bg-green-300 text-white p-2">
{{ $success }}
</div>
@endif
@foreach ($fields as $field)
<div class="p-2">
<label>{{ $field['display'] }}</label>
<div class="p-1">{!! $field['field'] !!}</div>
@if ($field['error'])
<p class="text-gray-500">{{ $field['error'] }}</p>
@endif
</div>
@endforeach
<button>{{ $form_button_label }}</button>
</s:form:create>
You can also use the shorthand syntax for form:create in="contact".
{{ form:contact }}
...
{{ /form:contact }}
<s:form:contact>
...
</s:form:contact>
Using this tag, Statamic will automatically take care of opening your form with a proper CSRF token.
<form method="POST" action="https://website.example/!/forms/contact">
<input type="hidden" name="_token" value="cN03woeRj5Q0GtlOj7GydsZcRwlyp9VLzfpwDFJZ">
...
</form>
It also provides helpers for rendering sections and fields, conditionally showing and hiding fields with logic, etc.
Rendering Fields#
Loop through the fields array using the form:fields tag to render your form's fields.
{{ form:contact }}
{{ form:fields }}
<div class="p-2">
<label>
{{ display }}
{{ if validate | contains:required }}
<sup class="text-red">*</sup>
{{ /if }}
</label>
<div class="p-1">{{ field }}</div>
{{ if error }}
<p class="text-gray-500">{{ error }}</p>
{{ /if }}
</div>
{{ /form:fields }}
<button>{{ form_button_label }}</button>
{{ /form:contact }}
<s:form:contact>
<s:form:fields>
<div class="p-2">
<label>
{{ $field['display'] }}
@if (in_array('required', $field['validate'] ?? []))
<sup class="text-red">*</sup>
@endif
</label>
<div class="p-1">{{ $field['field'] }}</div>
@if ($field['error'])
<p class="text-gray-500">{{ $field['error'] }}</p>
@endif
</div>
</s:form:fields>
<button>{{ $form_button_label }}</button>
</s:form:contact>
Each item in this fields array contains the following data:
Fields Array Variables#
| Variable | Type | Description |
|---|---|---|
id |
string | A unique ID for the field's input, like contact-form-email-field. Handy for a label's for attribute. |
display |
string | User-friendly field label configured in blueprint |
instructions |
string | User-friendly instructions label configured in blueprint |
field |
string | Pre-rendered field HTML based on the fieldtype |
type |
string | Name of the fieldtype |
handle |
string | Blueprint handle for the field |
name |
string | Input name for submitting the field |
value |
mixed | Field value, which respects both old and default |
default |
mixed | Default field value as assigned by blueprint |
old |
mixed | Old field value from an unsuccessful submission |
error |
string | Error message from an unsuccessful submission |
validate |
array | Contains an array of validation rules |
width |
string | Width of the field assigned in the blueprint |
is_informative |
boolean | true for informative fields like headings, banners, and paragraphs that don't collect data. Use it to skip rendering a label and error. |
Pre-rendered Field HTML#
Using the field variable will intelligently render inputs as inputs, textareas as textareas, and snozzberries as snozzberries.
You can customize these pre-rendered snippets by running php artisan vendor:publish --tag=statamic-forms. It will expose editable templates snippets in your views/vendor/statamic/forms/fields directory that will be used by each fieldtype.
Pre-rendered snippets are implemented in Antlers by default. Blade versions will be used instead if your statamic.templates.language config is set to blade.
This approach, combined with the Form Builder, will give you something very similar to a traditional "Form Builder" from other platforms.
Example
{{ form:fields }}
<div class="mb-2">
<label class="block">{{ display }}</label>
{{ field }}
</div>
{{ /form:fields }}
<s:form:fields>
<div class="mb-2">
<label class="block">{{ $field['display'] }}</label>
{{ $field['field'] }}
</div>
</s:form:fields>
<div class="mb-2">
<label class="block">Name</label>
<input type="text" name="name" value="">
</div>
<div class="mb-2">
<label class="block">Email Address</label>
<input type="text" name="email" value="">
</div>
<div class="mb-2">
<label class="block">Note</label>
<textarea name="message"></textarea>
</div>
Rendering Sections#
If your form has multiple sections, you can loop over the sections array to render them as well.
{{ form:contact }}
{{ sections }}
<fieldset>
<legend>{{ display }}</legend>
{{ form:fields }}
...
{{ /form:fields }}
</fieldset>
{{ /sections }}
<button>{{ form_button_label }}</button>
{{ /form:contact }}
<s:form:contact>
@foreach($sections as $section)
<fieldset>
<legend>{{ $section['display'] }}</legend>
<s:form:fields :section="$section">
...
</s:form:fields>
</fieldset>
@endforeach
<button>{{ $form_button_label }}</button>
</s:form:contact>
Each item in the sections array contains the following data configurable in the form's blueprint.
| Variable | Type | Description |
|---|---|---|
display |
string | User-friendly section label |
instructions |
string | User-friendly section instructions |
fields |
array | An array of fields defined within that section |
Logic (Conditional Fields)#
You may conditionally show and hide fields by configuring logic on your fields in the Form Builder. Once configured, by including the necessary front-end scripts and enabling JavaScript on the form:create tag, all of the logic will Just Work™.
Statamic includes an Alpine.js driver or you can build your own custom JS driver to wire up whichever framework you prefer.
Including the Scripts#
For our Alpine.js example, the first step is to include Alpine, as well as Statamic's front-end helpers.js script:
<script src="/vendor/statamic/frontend/js/helpers.js"></script>
These can be added to your layout just before your </body> tag. Alternatively, you could also work these into your Vite build, but this is the simplest way.
Enabling the JS Driver#
The next step is to enable the Alpine JS driver via the js="alpine" parameter.
{{ form:contact js="alpine" }}
...
{{ /form:contact }}
<s:form:contact js="alpine">
...
</s:form:contact>
This will generate an Alpine component, with automatic x-data handling that will respect old input when there are validation errors, etc.
Wiring Up the Fields#
Finally, you will need to wire up the fields. With Alpine, this is done using x-model.fill on the input to keep it in sync with the component, as well as an x-if to conditionally render the input and its label.
<template x-if="{{ show_field['name'] }}">
<div class="p-2">
<label>Name</label>
<input type="text" name="name" value="{{ old:name }}" x-model.fill="name" />
</div>
</template>
<template x-if="{{ $show_field['name'] }}">
<div class="p-2">
<label>Name</label>
<input type="text" name="name" value="{{ old('name') }}" x-model.fill="name" />
</div>
</template>
The x-model should reference the field's handle, and the x-if should reference the appropriate show_field JS generated by Statamic; In this case, x-model.fill="name" and x-if="{{ show_field['name'] }}" respectively.
The .fill modifier ensures the input's value attribute (such as old input, or the field's current value) is used to populate the Alpine model on load, rather than being overridden by it.
For nested fields, you can get show_field JS by passing the whole dotted handle as the key, ie) x-if="{{ show_field['field_group.nested_field']}}".
Wiring Up Dynamically Rendered Fields#
If you are rendering your fields using the fields loop, your template might look something like this:
{{ form:fields }}
<template x-if="{{ show_field }}">
<div class="p-2">
<label>{{ display }}</label>
<div class="p-1">{{ field }}</div>
</div>
</template>
{{ /form:fields }}
<s:form:fields>
<template x-if="{{ $field['show_field'] }}">
<div class="p-2">
<label>{{ $field['display'] }}</label>
<div class="p-1">{{ $field['field'] }}</div>
</div>
</template>
</s:form:fields>
The pre-rendered {{ field }} input will automatically render x-model.fill for you, but you'll still need to wrap your input and its label with an x-if="{{ show_field }}, as shown above.
Scoping Your Alpine Data#
If you are using other Alpine components in your form or on your page, the included Alpine driver allows you to scope the generated x-data to prevent conflicts with your other components. To do this, provide a scope key when enabling the JS driver.
{{ form:contact js="alpine:contact_form" }}
...
{{ /form:contact }}
<s:form:contact js="alpine:contact_form">
...
</s:form:contact>
The above will nest your form fields in a contact_form object within the generated x-data.
Custom JS Drivers#
Should you need to work with another JS framework for handling logic and form state in realtime, we've provided a few tools to help you build your own JS driver.
Creating the Driver#
To write a custom JS form driver, create a class and extend Statamic\Forms\JsDrivers\AbstractJsDriver.
<?php
namespace App\Forms;
use Statamic\Forms\JsDrivers\AbstractJsDriver;
use Statamic\Statamic;
class RadJs extends AbstractJsDriver
{
public function addToFormAttributes()
{
return [
'r-data' => Statamic::modify($this->getInitialFormData())->toJson()->entities(),
];
}
public function addToRenderableFieldAttributes($field)
{
$attributes = [];
if ($field->fieldtype()->hasJsDriverDataBinding()) {
$attributes['r-model'] => $field->handle(),
}
return $attributes;
}
public function addToRenderableFieldData($field, $data)
{
$conditions = Statamic::modify($field->conditions())->toJson()->entities();
return [
'show_field' => 'Statamic.$conditions.showField('.$conditions.', $data)',
];
}
}
In this above example, we provide r-data and r-model attributes for a fictional framework called Rad.js, as well as show_field conditional logic for each renderable field.
Registering the Driver#
To register your custom JS form driver class, simply call its static register() method from within a service provider.
public function register()
{
\App\Forms\RadJs::register();
}
Driver Requirements#
The only true requirement of your custom driver is that you return show_field javascript from the addToRenderableFieldData() method, so that the user can wire up show_field conditional logic as per the documentation above.
Available Methods and Properties#
Take a look at the AbstractJsDriver class to see what is available to you, but here is a list of available methods and properties at a glance:
Definable Render Methods#
- Define an
addToFormData($data)method in your class to add to the available data within theform:createtag pair. - Define an
addToFormAttributes()method in your class to add custom HTML attributes to your<form>element. - Define an
addToRenderableFieldData($field, $data)method in your class to add to the available data for each field within thefieldsloop. - Define an
addToRenderableFieldAttributes($field)method in your class to add custom HTML attributes to each pre-renderedfieldfield input within thefieldsloop. - Define a
render($html)method to control the overall rendering of your form component HTML.
Callable Helper Methods#
- Call
$this->getInitialFormData()to get the initial form field values from the server, while respecting old input when there are validation errors, etc.
Driver Properties#
- The
$this->formproperty gives you access to the relevantStatamic\Forms\Formobject anywhere within your driver class. - The
$this->optionsproperty gives you access to the passed driver options.
Driver Options#
You can also pass comma-delimited options into the js parameter like so:
{{ form:contact js="radjs:foo:bar" }}
...
{{ /form:contact }}
<s:form:contact js="radjs:foo:bar">
...
</s:form:contact>
Within your driver class, you'll be able to access $this->options to retrieve an array of options (ie. ['foo', 'bar'] in the example above).
The Helpers.js Script#
The Statamic.$conditions.showField(conditions, data) helper is available when including the helpers.js script:
<script src="/vendor/statamic/frontend/js/helpers.js"></script>
The conditions parameter accepts your field's conditions, typically generated using $field->conditions().
The data parameter accept's an object containing your form's values, typically stored somewhere within your form's javascript state.
This JS helper will evaluate your field conditions in realtime against your form's field values to determine whether or not the field in question should be shown.
Precognition#
Statamic supports using Laravel Precognition in forms.
Here is a basic example that uses Alpine.js for the Precognition validation, and a regular form submission. This is a starting point that you may customize as needed. For instance, you might prefer to use AJAX to submit the form.
Note that js="alpine_precognition" is used rather than just alpine.
{{ form:contact js="alpine_precognition" }}
{{ if success }}
Success!
{{ /if }}
<template x-if="form.hasErrors">
<div>
Errors!
<ul>
<template x-for="error in form.errors">
<li x-text="error"></li>
</template>
</ul>
</div>
</template>
{{ fields }}
<label>{{ display }}</label>
{{ field }}
<small x-show="form.invalid('{{ handle }}')" x-text="form.errors.{{ handle }}"></small>
{{ /fields }}
<button :disabled="form.processing">{{ form_button_label }}</button>
{{ /form:contact }}
<s:form:contact js="alpine_precognition">
@if ($success) Success! @endif
<template x-if="form.hasErrors">
<div>
Errors!
<ul>
<template x-for="error in form.errors">
<li x-text="error"></li>
</template>
</ul>
</div>
</template>
@foreach ($fields as $field)
<label>{{ $field['display'] }}</label>
{!! $field['field'] !!}
<small
x-show="form.invalid('{{ $field['handle'] }}')"
x-text="form.errors.{{ $field['handle'] }}"
></small>
@endforeach
<button :disabled="form.processing">{{ $form_button_label }}</button>
</s:form:contact>
To build on the regular form submission example above, here's an example for AJAX submission.
- The third argument of the
jsparameter defines the Alpine component. - The native form's submit event is listened for, prevented, and the component's
submitmethod is called instead.
{{ form:contact
js="alpine_precognition:form:contact"
@submit.prevent="submit"
}}
<s:form:contact
js="alpine_precognition:form:contact"
@submit.prevent="submit"
>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('contact', (data) => ({
...data,
submit() {
this.form.submit().then(response => {
this.form.reset();
console.log("Success")
}).catch(error => {
console.log(error);
});
}
}));
});
</script>
The user form tags (login, register, profile, and password) also support Precognition, but are wired up a little differently. See each tag's documentation for details.
Submitting with AJAX#
To submit the form with AJAX, be sure to pass all the form inputs in with the submission, as Statamic sets _token and _params, both of which are required.
You'll also need to set your AJAX library's X-Requested-With header to XMLHttpRequest.
The URL endpoint to send the request to is /!/forms/{form-handle}. You can configure the action route prefix which defaults to ! in config/statamic/routes.php.
A successful submission responds with JSON containing:
| Key | Description |
|---|---|
success |
Always true. |
submission_created |
false when the submission was silently rejected, like when the honeypot is filled. |
submission |
The submitted values. |
redirect |
The URL to redirect to, if there is one. |
next_page |
For Forms Pro multi-page forms, the ID of the next page. null on the last page. |
A failed submission responds with a 400 status, along with errors (an array of all error messages) and error (the first error message for each field, keyed by field handle).
Axios example#
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
form = document.getElementById('form');
// On submit...
axios.post(form.action, new FormData(form))
.then(response => {
console.log(response.data)
});
Parameters
handle|is|in|form|formset
Specify the name of the form. Only required if you do not use the form:set tag, or don't have a form defined in the current context.
redirect
The location your user will be taken after a successful form submission. If left blank, the user will stay on the same page.
error_redirect
The location your user will be taken after a failed form submission. If left blank, the user will stay on the same page.
allow_request_redirect
When true, the redirect and error_redirect parameters will get overridden by redirect and error_redirect query parameters in the URL. For example, ?redirect=/thanks
csrf
When false, the hidden name="_token" attribute won't be added to the form so you can use other ways of providing the token. Defaults to true.
files
When true, the enctype="multipart/form-data" attribute will be rendered on your <form> tag for file uploads.
js
Enable logic using one of the provided JS drivers.
HTML Attributes
Set HTML attributes as if you were on an HTML element. For example, class="required" id="contact-form".
Variables
| Variable | Type | Description |
|---|---|---|
fields |
array |
An array of available fields for rendering. |
sections |
array |
An array of the current page's sections, each containing its fields, for rendering. |
honeypot |
string |
The name of the form's honeypot field. |
form_config |
array |
Any extra config values added to the form's settings by addons using |
form_status |
string |
The status of the form. Either |
form_restricted |
boolean |
Whether the form is restricted — it's closed, its submission limit has been reached, or it requires login and the visitor is logged out. |
form_restriction_message |
string |
The message to show when the form is restricted. |
form_pages |
array |
For Forms Pro multi-page forms. An array of the form's pages, each with an |
form_page |
array |
For Forms Pro multi-page forms. The current page, with the same variables as each item in |
form_button_label |
string |
The label for the current page's submit button, set in the Form Builder. Defaults to "Next", or "Submit" on the last page. |
form_previous_page_label |
string |
For Forms Pro multi-page forms. The label for the current page's previous button, when it's enabled. |
form_previous_page_url |
string |
For Forms Pro multi-page forms. The URL of the previous page. Set on every page except the first, so check |
errors |
array |
An indexed array of any validation errors upon submission. For example: |
error |
array |
An array of validation errors indexed by field name. For example: |
old |
array |
An array of submitted values from the previous request. Used for re-populating fields if there are validation errors. |
success |
string |
A success message, usually used in a condition to check of a form submission was successful. |
submission_created |
boolean |
A success boolean, which differs from |