2017 © Pedro PelĂĄez
 

craft-plugin contact-form

Add a simple contact form to your Craft CMS site

image

craftcms/contact-form

Add a simple contact form to your Craft CMS site

  • Saturday, July 28, 2018
  • by brandonkelly
  • Repository
  • 17 Watchers
  • 264 Stars
  • 10,213 Installations
  • PHP
  • 11 Dependents
  • 0 Suggesters
  • 83 Forks
  • 6 Open issues
  • 14 Versions
  • 43 % Grown

The README.md

Contact Form for Craft CMS

This plugin allows you to add an email contact form to your website., (*1)

Requirements

This plugin requires Craft CMS 4.0.0+ or 5.0.0+., (*2)

Installation

You can install this plugin from the Plugin Store or with Composer., (*3)

From the Plugin Store

Go to the Plugin Store in your project’s Control Panel and search for “Contact Form”. Then click on the “Install” button in its modal window., (*4)

With Composer

Open your terminal and run the following commands:, (*5)

# go to the project directory
cd /path/to/my-project.test

# tell Composer to load the plugin
composer require craftcms/contact-form

# tell Craft to install the plugin
php craft plugin/install contact-form

Usage

Your contact form template can look something like this:, (*6)

{% macro errorList(errors) %}
    {% if errors %}
        {{ ul(errors, {class: 'errors'}) }}
    {% endif %}
{% endmacro %}

{% set submission = submission ?? null %}



{{ csrfInput() }} {{ actionInput('contact-form/send') }} {{ redirectInput('contact/thanks') }}

{{ input('text', 'fromName', submission.fromName ?? '', { id: 'from-name', autocomplete: 'name', }) }} {{ submission ? _self.errorList(submission.getErrors('fromName')) }}

{{ input('email', 'fromEmail', submission.fromEmail ?? '', { id: 'from-email', autocomplete: 'email', }) }} {{ submission ? _self.errorList(submission.getErrors('fromEmail')) }}

{{ input('text', 'subject', submission.subject ?? '', { id: 'subject', }) }} {{ submission ? _self.errorList(submission.getErrors('subject')) }}

{{ tag('textarea', { text: submission.message ?? '', id: 'message', name: 'message', rows: 10, cols: 40, }) }} {{ submission ? _self.errorList(submission.getErrors('message')) }}

The only required fields are fromEmail and message. Everything else is optional., (*7)

Redirecting after submit

If you have a redirect hidden input, the user will get redirected to it upon successfully sending the email. The following variables can be used within the URL/path you set:, (*8)

  • {fromName}
  • {fromEmail}
  • {subject}

For example, if you wanted to redirect to a contact/thanks page and pass the sender’s name to it, you could set the input like this:, (*9)

{{ redirectInput('contact/thanks?from={fromName}') }}

On your contact/thanks.html template, you can access that from parameter using craft.app.request.getQueryParam():, (*10)

<p>Thanks for sending that in, {{ craft.app.request.getQueryParam('from') }}!</p>

Note that if you don’t include a redirect input, the current page will get reloaded., (*11)

Displaying flash messages

When a contact form is submitted, the plugin will set a notice (Craft 4) or success (Craft 5+) flash message on the user session. You can display it in your template like this:, (*12)

{% if craft.app.session.hasFlash('success') %}
    <p class="message success">{{ craft.app.session.getFlash('success') }}</p>
{% elseif craft.app.session.hasFlash('error') %}
    <p class="message error">{{ craft.app.session.getFlash('error') }}</p>
{% endif %}

Adding additional fields

You can add additional fields to your form by splitting your message field into multiple fields, using an array syntax for the input names:, (*13)



<textarea rows="10" cols="40" id="message" name="message[body]">{{ submission.message.body ?? '' }}</textarea>

<input id="phone" type="text" name="message[Phone]" value="">

What services are you interested in?

<label><input type="checkbox" name="message[Services][]" value="Design"> Design</label> <label><input type="checkbox" name="message[Services][]" value="Development"> Development</label> <label><input type="checkbox" name="message[Services][]" value="Strategy"> Strategy</label> <label><input type="checkbox" name="message[Services][]" value="Marketing"> Marketing</label>

If you have a primary “Message” field, you should name it message[body], like in that example., (*14)

An email sent with the above form might result in the following message:, (*15)

• Name: John Doe
• Email: example@email.com
• Phone: (555) 123-4567
• Services: Design, Development

Hey guys, I really loved this simple contact form (I'm so tired of agencies
asking for everything but my social security number up front), so I trust
you guys know a thing or two about usability.

I run a small coffee shop and we want to start attracting more freelancer-
types to spend their days working from our shop (and sipping fine coffee!).
A clean new website with lots of social media integration would probably
help us out quite a bit there. Can you help us with that?

Hope to hear from you soon.

Cathy Chino

By default, there’s no restriction on which keys can be included on message. You can limit which fields are allowed using the allowedMessageFields setting in config/contact-form.php:, (*16)

<?php

return [
    'allowedMessageFields' => ['Phone', 'Services'],
];

Overriding plugin settings

If you create a config file in your config/ folder called contact-form.php, you can override the plugin’s settings in the Control Panel. Since that config file is fully multi-environment aware, this is a handy way to have different settings across multiple environments., (*17)

Here’s what that config file might look like along with a list of all of the possible values you can override., (*18)

<?php

return [
    'toEmail'             => 'bond@007.com',
    'prependSubject'      => '',
    'prependSender'       => '',
    'allowAttachments'    => false,
    'successFlashMessage' => 'Message sent!'
];

Dynamically adding email recipients

You can programmatically add email recipients from your template by adding a hidden input field named toEmail like so:, (*19)

<input type="hidden" name="toEmail" value="{{ 'me@example.com'|hash }}">

If you want to add multiple recipients, you can provide a comma separated list of emails like so:, (*20)

<input type="hidden" name="toEmail" value="{{ 'me@example.com,me2@example.com'|hash }}">

Then from your config/contact-form.php config file, you’ll need to add a bit of logic:, (*21)

<?php

$config = [];
$request = Craft::$app->request;

if (
    !$request->getIsConsoleRequest() &&
    ($toEmail = $request->getValidatedBodyParam('toEmail')) !== null
) {
    $config['toEmail'] = $toEmail;
}

return $config;

In this example if toEmail does not exist or fails validation (it was tampered with), the plugin will fallback to the “To Email” defined in the plugin settings, so you must have that defined as well., (*22)

File attachments

If you would like your contact form to accept file attachments, follow these steps:, (*23)

  1. Go to Settings → Contact Form in the Control Panel, and make sure the plugin is set to allow attachments.
  2. Make sure your opening HTML <form> tag contains enctype="multipart/form-data".
  3. Add a <input type="file" name="attachment"> to your form.
  4. If you want to allow multiple file attachments, use multiple <input type="file" name="attachment[]" multiple> inputs.

Ajax form submissions

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:, (*24)

$('#my-form').submit(function(ev) {
    // Prevent the form from actually submitting
    ev.preventDefault();

    // Send it to the server
    $.post({
        url: '/',
        dataType: 'json',
        data: $(this).serialize(),
        success: function(response) {
            $('#thanks').text(response.message).fadeIn();
        },
        error: function(jqXHR) {
          // The response body will be an object containing the following keys:
          // - `message` – A high level message for the response
          // - `submission` – An object containing data from the attempted submission
          // - `errors` – An object containing validation errors from the submission, indexed by attribute name
          alert(jqXHR.responseJSON.message);
        }
    });
});

The afterValidate event

Modules and plugins can be notified when a submission is being validated, providing their own custom validation logic, using the afterValidate event on the Submission model:, (*25)

use craft\contactform\models\Submission;
use yii\base\Event;

// ...

Event::on(Submission::class, Submission::EVENT_AFTER_VALIDATE, function(Event $e) {
    /** @var Submission $submission */
    $submission = $e->sender;

    // Make sure that `message[Phone]` was filled in
    if (empty($submission->message['Phone'])) {
        // Add the error
        // (This will be accessible via `message.getErrors('message.phone')` in the template.)
        $submission->addError('message.phone', 'A phone number is required.');
    }
});

The beforeSend event

Modules and plugins can be notified right before a message is sent out to the recipients using the beforeSend event. This is also an opportunity to flag the message as spam, preventing it from getting sent:, (*26)

use craft\contactform\events\SendEvent;
use craft\contactform\Mailer;
use yii\base\Event;

// ...

Event::on(Mailer::class, Mailer::EVENT_BEFORE_SEND, function(SendEvent $e) {
    $isSpam = // custom spam detection logic...

    if ($isSpam) {
        $e->isSpam = true;
    }
});

The afterSend event

Modules and plugins can be notified right after a message is sent out to the recipients using the afterSend event., (*27)

use craft\contactform\events\SendEvent;
use craft\contactform\Mailer;
use yii\base\Event;

// ...

Event::on(Mailer::class, Mailer::EVENT_AFTER_SEND, function(SendEvent $e) {
    // custom logic...
});

Using a “Honeypot” field

Support for the honeypot captcha technique to fight spam has been moved to a separate plugin that complements this one., (*28)

The Versions

28/07 2018

v2.x-dev

2.9999999.9999999.9999999-dev

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 form cms contact craftcms

19/07 2018

2.2.2

2.2.2.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 form cms contact craftcms

19/07 2018

2.2.1

2.2.1.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 form cms contact craftcms

18/07 2018

2.2.0

2.2.0.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 form cms contact craftcms

02/05 2018

dev-feature/name-field-rendering-126

dev-feature/name-field-rendering-126

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 form cms contact craftcms

12/04 2018

dev-bugfix/silent-failing-95

dev-bugfix/silent-failing-95

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 form cms contact craftcms

27/03 2018

dev-bugfix/wall-of-text-118

dev-bugfix/wall-of-text-118

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

26/03 2018

dev-bugfix/contact-form-escape-HTML-104

dev-bugfix/contact-form-escape-HTML-104

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

05/12 2017

2.1.1

2.1.1.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

13/10 2017

2.1.0

2.1.0.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

15/09 2017

2.0.3

2.0.3.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

07/07 2017

2.0.2

2.0.2.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

13/06 2017

2.0.1

2.0.1.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms

17/05 2017

2.0.0

2.0.0.0

Add a simple contact form to your Craft CMS site

  Sources   Download

MIT

The Requires

 

yii2 cms craftcms