Free Form Builder with Database Integration, successor of Free Contact Form Plugin featured on Straight Up Craft, (*1)
, (*2)
Craft CMS 4.x
Use composer require xpertbot/craft-wheelform "^3.2"
, (*3)
Craft CMS 3.x
Use composer require xpertbot/craft-wheelform "^2.7"
, (*4)
Requirements
This plugin requires Craft CMS 5.0.0 or later, (*5)
Installation
To install the plugin, follow these instructions., (*6)
-
Open your terminal and go to your Craft project:, (*7)
cd /path/to/project
-
Then tell Composer to load the plugin:, (*8)
composer require xpertbot/craft-wheelform
-
In the Control Panel, go to Settings â Plugins and click the âInstallâ button for Wheel Form., (*9)
Features
- reCaptcha Validation
- Export CSV File
- Custom Email HTML Template
- Template variables for easy development
- Email Validation based on field type selected
- Form Field Type for sections
- Required Fields
- Checkbox options
- File extension restriction
- Honeypot Field
- Ajax and Redirect friendly
- Send Form submissions to multiple emails
- Advanced Permissions per form
- Reordering of fields
- Save Uploaded files to Asset Manager
- Multiple Translations
- Export / Import Fields between different websites
- Dynamic email notifications
Usage
After successful installation go to Plugin Settings and add the email you would like the forms to send FROM
. As well as set other useful settings., (*10)
Forms are administered at the forms panel main settings. Set where this form should be submitting TO
as well as name of the form., (*11)
Field Settings can be set as Required or not, for validation purposes., (*12)
Current Field types supported are:
* Text
* Textarea
* Email
* Number
* Checkboxes
* Radio
* Select
* Hidden
* File
* List
* HTML, (*13)
Template Variables
-
wheelform, (*14)
- settings
- form
- recaptcha
- open()
- close()
- fields
- type
- name
- label
- items
- fieldClass
- containerClass
- required
- order
- value
- options
- displayLabel
- entries
- getErrors()
- lastSubmission
-
wheelformErrors (Array of errors based on field name, form, recaptcha, honeypot)., (*15)
-
values (Array of User submitted values based on field name)., (*16)
These are configuration opens you can pass to wheelform.form
to configure your form., (*17)
-
id
: Required ID of the form being used.
-
redirect
: URL where form will redirect to after a successful submission.
-
registerScripts
: Boolean to load Scripts before wheelform.open
call (This is useful for caching forms and templates). Defaults to False.
-
refreshCsrf
: Boolean to load Javascript that will refresh the CSRF token for the form on the current page (This is useful for caching forms and templates). In order for this to work form.open()
needs to be outside the {% cache %}
block.
-
submitForm
: Configuration options for the submitButton. Example:
{# SubmitButton options:
"type" can be button, or input
"html" attribute takes precedence over the other properties,
"attributes" is an easy way to add attributes to the button, all attributes are optional #}
submitButton: {
"type": "button",
"label": "Send", // Text displayed for the button
"attributes": { // Array of attributes for the Button. Same as Form
"class": "btn btn-success",
"id": "submit-btn",
"data-submit": "Foo",
},
"html": "<span><button>Custom Button</button></span>", // Custom HTML Overwrittes any other options and will render it as final.
}
-
action
: String to overwritte where the form submits to. This is useful if you need to overwrite it with Javascript. Defaults to empty string.
-
attributes
: {Key: Value} Array of Attributes for the current form. Defaults to empty array. Note: Form attributes take presedence over default values. Example:
{#
- Special Attribute: `csrf`: {boolean}, enables/disables csrf token field, disable if you would like to implement your own csrf token generation. Example:
{{ form.open('', {
'csrf': false,
}) }}
{{ craft.blitz.csrfInput() }}
... Rest of form template ...
#}
-
method
: String to overwritte the form HTML method
attribute. Defaults to "POST"
{{ form.open("", {
'novalidate': 'novalidate',
'id':'custom-form',
'class': 'custom-form',
}, "POST") }}
Field Service options
-
getFileExtensions
If current Field Type is "file" you can retrieve the current "File Extension Restrictions" set on that field.
Dynamic Email notifications
- "Email Subject", "Submit Message", "User Notification Subject" and "User Notification Message" form settings can use dynamic field values by referencing the field "name" between square brackets. e.g. "You received a form submission from
[email]
" where email
is the name
of a field in your form.
Template Structure
Your form template can look something like this:, (*18)
{% macro errorList(errors) %}
{% if errors %}
{% for error in errors %}
- {{ error }}
{% endfor %}
{% endif %}
{% endmacro %}
{% from _self import errorList %}
{% set form = wheelform.form({
id: 1,
redirect: 'contact/thanks'
}) %}
{{ form.open() }}
{{ wheelformErrors['form'] is defined ? errorList(wheelformErrors['form']) }}
{{ wheelformErrors['recaptcha'] is defined ? errorList(wheelformErrors['recaptcha']) }}
{{ wheelformErrors['honeypot'] is defined ? errorList(wheelformErrors['honeypot']) }}
{% for field in form.fields %}
{{ field.render() }}
{{ wheelformErrors[field.name] is defined ? errorList(wheelformErrors[field.name]) }}
{% endfor %}
{{ form.close() }}
Advanced templating:, (*19)
{% macro errorList(errors) %}
{% if errors %}
{% for error in errors %}
- {{ error }}
{% endfor %}
{% endif %}
{% endmacro %}
{% from _self import errorList %}
{% set form = wheelform.form({
id: 1,
redirect: 'contact/thanks',
}) %}
{{ form.open() }}
{{ wheelformErrors['form'] is defined ? errorList(wheelformErrors['form']) }}
{{ wheelformErrors['recaptcha'] is defined ? errorList(wheelformErrors['recaptcha']) }}
{{ wheelformErrors['honeypot'] is defined ? errorList(wheelformErrors['honeypot']) }}
{% for field in form.fields %}
{% switch field.type %}
{% case "checkbox" %}
<div class="form-checkbox">
{% for item in field.items %}
<label><input class="checkbox" type="checkbox" value="{{ item }}" {{values[field.name] is defined and item in values[field.name] ? ' checked="checked"' : '' }} name="{{field.name}}[]" id=""/>{{item}}</label>
{% endfor %}
</div>
{% case "radio" %}
<div class="form-radio">
{% for item in field.items %}
<input class="radio" type="radio" value="{{ item }}" {{values[field.name] is defined and item == values[field.name] ? ' checked="checked"' : '' }} name="{{field.name}}" id=""/>
<label>{{item}}</label>
{% endfor %}
</div>
{% case "select" %}
<div class="form-select">
<select id="wf-select" name="{{field.name}}" class="wf-field {{field.fieldClass}}">
{% for item in field.items %}
<option value="{{ item }}" {{values[field.name] is defined and item == values[field.name] ? 'selected="selected"' : '' }}>{{item}}</option>
{% endfor %}
</select>
</div>
{% case "file" %}
<div class="form-group">
<label>{{field.label}}</label>
<input type="file" name="{{field.name}}" id=""/>
</div>
{% case "textarea" %}
<div class="form-group">
<label>{{field.label}}</label>
<textarea class="form-control" name="{{field.name}}" id="">{{ values[field.name] ?? '' }}</textarea>
</div>
{% case "list" %}
<div class="form-group">
<label>{{field.label}}</label>
<input type="text" name="{{field.name}}[]" id=""/>
<script>//Javascript to handle adding fields</script>
</div>
{% default %}
<div class="form-group">
<label>{{field.label}}</label>
<input class="form-control" type="{{field.type}}" value="{{ values[field.name] ?? '' }}" name="{{field.name}}" id=""/>
</div>
{% endswitch %}
{{ wheelformErrors[field.name] is defined ? errorList(wheelformErrors[field.name]) }}
{% endfor %}
{% if form.recaptcha %}
<div>
<script src="https://www.google.com/recaptcha/api.js"></script>
<!-- Production captcha -->
<div class="g-recaptcha" data-sitekey="{{wheelform.getSettings('recaptcha_public')}}"></div>
</div>
{% endif %}
<button class="btn btn-success" id="submit">Send</button>
</form>
If you want to stick to HTML and not use the variables:, (*20)
{% macro errorList(errors) %}
{% if errors %}
{% for error in errors %}
- {{ error }}
{% endfor %}
{% endif %}
{% endmacro %}
{% from _self import errorList %}
{{ wheelformErrors['form'] is defined ? errorList(wheelformErrors['form']) }}
<form method="post" action="" accept-charset="UTF-8" novalidate="" enctype="multipart/form-data">
{{ csrfInput() }}
<input type="hidden" name="action" value="wheelform/message/send">
<input type="hidden" name="form_id" value="1">
<input type="hidden" name="redirect" value="{{ 'contact/thanks'|hash }}">
<h3><label for="from-name">Your Name</label></h3>
<input id="from-name" type="text" name="name" value="{{ values['name'] ?? '' }}">
{{ wheelformErrors['name'] is defined ? errorList(wheelformErrors['name']) }}
<h3><label for="from-email">Your Email</label></h3>
<input id="from-email" type="email" name="email" value="{{ values['email'] ?? '' }}">
{{ wheelformErrors['email'] is defined ? errorList(wheelformErrors['email']) }}
<h3><label for="phone">Phone</label></h3>
<input id="phone" type="text" name="phone" value="{{ values['phone'] ?? '' }}">
{{ wheelformErrors['phone'] is defined ? errorList(wheelformErrors['phone']) }}
<label><input type="checkbox" name="favorite_topping[]" value="Chocolate">Chocolate</label>
<label><input type="checkbox" name="favorite_topping[]" value="Vanilla">Vanilla</label>
<label><input type="checkbox" name="favorite_topping[]" value="Strawberry">Strawberry</label>
{{ wheelformErrors['favorite_topping'] is defined ? errorList(wheelformErrors['favorite_topping']) }}
<h3><label for="message">Message</label></h3>
<textarea rows="10" cols="40" id="message" name="message">{{ values['message'] ?? '' }}</textarea>
{{ wheelformErrors['message'] is defined ? errorList(wheelformErrors['message']) }}
<input type="file" name="user_file" id="user_filer">
{# if using recaptcha settings #}
<div class="recaptcha-container">
<script src="https://www.google.com/recaptcha/api.js"></script>
<div class="g-recaptcha" data-sitekey="{{ site_key }}">
</div>
</div>
<input type="submit" value="Send">
</form>
Redirecting after submit
If you have a âredirectâ hidden input, the user will get redirected to it upon successfully sending the email., (*21)
Note that if you donât include a redirect
input, the current page will get reloaded., (*22)
Displaying flash messages
When a contact form is submitted, the plugin will set a success
flash message on the user session. This is so, you can have a success message after the form has been submitted and can be displayed on redirected page.
The available flash variables are:
wheelformSubmittedForm
- ID of submitted form
wheelformSuccess
- message to display
You can display it in your template like this:, (*23)
{% if craft.app.session.hasFlash('wheelformSuccess') %}
<p class="message success">{{ craft.app.session.getFlash('wheelformSuccess') }}</p>
{% endif %}
You can assign a Field Type to your sections where Users can select which form to display based on a Dropdown. This field will return a wheelform.form
template service (same as other examples) that belongs to the form selected on the Admin Panel. if you need to customize it you can use the setConfig
variable to modify the default behaviour., (*24)
{% set form = entry.formField.setConfig({
redirect: 'contact/thanks',
attributes: {
'novalidate':"novalidate",
'id':'field-form',
'class': 'field-form',
},
}) %}
Displaying the last/current submission
Similar to the flash message (will only be available after submission), when a contact form is submitted the plugin will store the values of the submitted form in the session and make it available (once) through the wheelform.lastSubmission
variable. You can use this in the template (typically in your re-direct page) like this:, (*25)
{% set submission = wheelform.lastSubmission %}
{% if submission %}
<dl>
{% for field in submission.fields %}
<dt>{{ field.label }}</dt>
<dd>{{ field.value }}</dd>
{% endfor %}
</dl>
{% endif %}
You also have available submission.id
, submission.formId
and submission.date
(Note: submission.date
is a DateTime object run it through date()
filter)., (*26)
Recaptcha V3
{# You need to add the Recaptcha Init before the form.open() #}
{# action is optional, action defaults to form URL #}
{{ wheelform.recaptchaV3({'action': 'contact-form'})}}
You can access existing submitted form entries on a form through the form.entries
property:, (*27)
{% set form = wheelform.form({ id: 1 }) %}
{# form.entries(start, limit) can be used for pagination purposes #}
{% set entries = form.entries %}
{# form.fields returns active form fields #}
{% set fields = form.fields %}
<
table>
<thead>
{% for field in fields %}
<th>{{ field.label }}</th>
{% endfor %}
<th>Date</th>
</thead>
<tbody>
{% for entry in entries %}
<tr data-id="{{ entry.id }}">
{% for field in fields %}
{% set current = entry.fields[field.name] %}
<td data-id="{{ current.name }}">{{ current.value }}</td>
{% endfor %}
<td data-id="date">{{ entry.date|date("m/d/Y") }}</td>
</tr>
{% endfor %}
</tbody>
You can access specific form entry by loading the form and requesting it by ID:, (*28)
{% set form = wheelform.form({ id: 1 }) %}
{% set entry = form.entry(id) %}
{% for field in entry.fields %}
<p>{{ field.value }}</p>
{% endfor %}
File attachments
If you would like your form to accept file attachments, follow these steps:, (*29)
- Make sure your opening HTML
<form>
tag contains enctype="multipart/form-data"
.
- Add a
<input type="file" name="{field_name}">
to your form.
File saving to asset Folder
On Plugin Settings select the Folder you would like to save files. Make sure Allow public URLs
option is turned on., (*30)
You can optionally post contact form submissions over Ajax if youâd like. Just send a POST request to your site with all of the same data that would normally be sent:, (*31)
JQuery, (*32)
$('#my-form').submit(function(ev) {
// Prevent the form from actually submitting
ev.preventDefault();
var data = $(this).serialize();
// Send it to the server
$.post('/wheelform/message/send',
data,
function(response) {
if (response.success) {
//reponse.message is the message saved in the Form Settings
$('#thanks').fadeIn();
} else {
// response.values will contain user submitted values
// response.errors will be an array containing any validation errors that occurred, indexed by field name
// e.g. response.error['email'] => ['Email is required', 'Email is invalid']
alert('An error occurred. Please try again.');
}
}
);
});
Basic Javascript using Axios and Babel with Webpack, (*33)
import axios from 'axios';
const contactForm = document.getElementById('contact-form');
if (contactForm) {
contactForm.addEventListener('submit', function(event) {
/**
* This prevents the default behaviour of the browser submitting
* the form so that we can handle things instead.
*/
event.preventDefault();
/**
* This gets the element which the event handler was attached to.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
*/
const form = event.currentTarget;
/**
* Hidden field named action
*/
const url = form.action.value;
/**
* This takes all the fields in the form and makes their values
* available through a `FormData` instance.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/FormData
*/
const formData = new FormData(form);
axios({
method: 'post',
url: url,
responseType: 'json',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
}
If using getCrsfInput() make sure you are submitting it with the rest of your form., (*34)
Recaptcha with Ajax
If implementing Recaptcha with Ajax, keep in mind that it is necessary after each Ajax request to refresh the recaptcha token to avoid an invalid recaptcha validation error (see issue 242)., (*35)
Example using Fetch API:, (*36)
const myRequest = new Request('endpoint.json', {
method: 'POST', // any allowed Method
param: value
});
fetch(myRequest)
.then((response) => response.json())
.then((data) => {
// Use respose `data` here
// Refresh Recaptcha token
wheelformProcessRecaptchaCallback()
});
If submitting Ajax request and need Meta Tags inside head
element you can use {{ wheelform.metaTags() }}
to generate the appropriate CSRF values., (*37)
Permissions
There are 4 different type of permissions ({Form Name} permissions are repeated per form on your website):
- Create new Form - Allows User / Group to see the "New Form" button and create new forms.
- Edit {Form Name} - Allows User / Group to see the form on the list of forms.
- {Form Name} Entries - Allows User / Group to view the Entries list.
- {Form Name} Settings - Allows User / Group to Edit the form settings., (*38)
- CSV Exporter can be based on entry date, under Admin > Utilities > Form Tools.
- Form Fields can be exported as a JSON file.
- Form Fields can be imported from a valid JSON file.
Delete Messages Cron Job
You can schedule a Cron Job on your server to run daily an check to Delete any old Messages values saved on your database. The cron Job Command is:
php var/www/yourwebsite/craft wheelform/message/purge
where var\www\yourwebsite\craft
is the path to the craft executable package., (*39)
The only configuration needed inside config\wheelform.php
is:, (*40)
return [
'purgeMessages' => true, //True / False value to allow Cron Job to go
'purgeMessagesDays' => 30, //Number of days messages should live in your database
];
Note: This action cannot be reverted., (*41)
Change the "From" Address based on each form, this will overwritte the General email set on the form settings., (*42)
- Create
wheelform.php
file inside Craft's configuration folder.
- Add and
array
with the key forms
with the ID
of the form you would like to overwrite as the key followed
by an array with the key from
. Example below:
return [
'forms' => [
// ID of form
3 => [
// This is the email to use for this specific form
'from' => 'form3@example.com',
],
5 => [
// This can also be an array with a custom name
'from' => [
'form5@example.com' => "Form 5 Custom Name",
]
]
]
];
Custom Email Template
Email Templates are Optional. Custom Twig templates can be used using these steps:, (*43)
- Create
wheelform.php
file inside Craft's config folder.
-
wheelform.php
expects an array of configuration settings to be returned. The options are:
-
template
: default template to use for all emails.
-
notification
: default notification template overwrite.
-
forms
: is an array that overwrites any settings specific to the form. The key on each array is the ID of the form to modify. (These settings take priority over anything else) (Note: This forms
key is the same as above for custom "From" Address)
return [
'template' => '_emails/custom',
'notification' => [
'template' => '_emails/notification',
'subject' => 'Default Notification Subject',
],
'forms' => [
1 => [
'template' => '_emails/form1_template',
'notification' => [
'template' => '_emails/notification2',
'subject' => 'Form specific Subject',
],
],
3 => [
'template' => '_emails/form3_template',
],
],
];
- Inside your templates you will have access to a
fields
array and notification_message
with the message set on the Form Administration Panel.
Example:
<html>
<body>
<h1>Custom Template</h1>
<ul>
{% for field in fields %}
<li>
<strong>{{ field.label }}:</strong>
{% switch field.type %}
{% case "file" %}
{# This is an object with file attributes #}
{{ field.value.name }}
{% case "checkbox" %}
{# Array of all choices selected #}
{{ field.value | join(',')}}
{% case "list" %}
{% if field.value %}
<ul>
{% for item in field.value %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endif %}
{% default %}
{# Text based items #}
{{ field. value }}
{% endswitch %}
</li>
{% endfor %}
</ul>
</body>
</html>
Skip attaching files to email
Inside wheelform.php
each form can have a flag to skip attaching email:, (*44)
return [
'forms' => [
1 => [
'skip_attachments' => true, // True/False value, leave empty if not needed.
],
],
];
Honeypot Field
Honeypot field is a field that is meant to be left blank by humans. Usually hidden by CSS. More information about Honeypot fields., (*45)
If not using {{ form.close() }}
helper tag make sure you add a text field with the name you used when creating the form. Then, hide it from the user using CSS or Javascript., (*46)
Render Honeypot (Optional)
If you need complete control of how the Honeypot field should behave. You can call {{ form.honeypot($type, $attributes = [], $returnString = false) }}
where:
- $type
: can be 1 of 3 types; text
, password
, hidden
.
- $attributes
: (Optional) an array of options for the field. E.G. {'autocomplete': 'none', 'class': 'comments-field'}
.
- $returnString
: (Optional) This will return the field HTML string for further manipulation, instead of template ready entities., (*47)
Events
(Note: this is mostly for developers that know basic PHP and Composer Packages), (*48)
beforeValidate
Event, this allows developers to validate the values and add custom errors. skipping the plugin validation altogether, this happens before the basic plugin vaidation., (*49)
afterValidate
Event, this allows developers to validate the Message and adjust the values and errors, this happens after the basic plugin vaidation, these changes cascade into the other Events and Mailers., (*50)
beforeSave
Event, this allows developers to modify the value Active Records objects before being saved to the database, these changes cascade into the other Events and Mailers., (*51)
beforeSend
Event, this allows developers to modify the fields being sent in an email, this event does not modify the values entered in the database. Only the fields being sent to the client., (*52)
afterSend
Event, Final Values sent to the user email, perfect for Third Party integrations and libraries., (*53)
beforeResponse
Event, event that modifies the response of the submission, good place to add Custom headers, dynamic success messages, or custom data to consume on the frontend., (*54)
You can also trigger other custom functionality such as gathering custom field values to add to a Third party service such as a Mailing list., (*55)
beforeSend
and afterSend
object is as follows:
Event
class properties:
* form_id
- Current ID of form being submitted, This allows developers some way to check what fields are being sent.
* subject
- Subject of the currnet form. This can be modified to make it customizable.
* message
- Associative Array of different fields with the values submitted.
* from
- Email Address message is being send From.
* to
- Email Address message is being send To (This can be an array of multiple emails).
* reply_to
- Email Address message can be Reply To.
* email_html
- Full HTML String that will be sent in the email. This overwrites other email templates.
* saveMessage
- Allow the message to be saved on the database (Default: True).
* sendMessage
- Allow the message to be sent (Default: True)., (*56)
Example Plugin to handle these events. wheelformhelper, (*57)
Translations
New translations can be submitted using the format inside the translations folder. (I will keep "es" translations up to date as much as possible, that can be a good starting point for your translations), (*58)