craftcms / contact-form
为您的Craft CMS网站添加简单的联系表单
Requires
- php: ^8.0.2
- craftcms/cms: ^4.0.0-beta.1|^5.0.0-beta.1
Requires (Dev)
- craftcms/ecs: dev-main
- craftcms/phpstan: dev-main
- craftcms/rector: dev-main
- 3.x-dev
- 3.1.0
- 3.0.1
- 3.0.0
- 3.0.0-beta.2
- 3.0.0-beta.1
- v2.x-dev
- 2.5.3
- 2.5.2
- 2.5.1
- 2.5.0
- 2.4.1
- 2.4.0
- 2.3.0
- 2.2.7
- 2.2.6
- 2.2.5
- 2.2.4
- 2.2.3
- 2.2.2
- 2.2.1
- 2.2.0
- 2.1.1
- 2.1.0
- 2.0.3
- 2.0.2
- 2.0.1
- 2.0.0
- dev-dependabot/composer/craftcms/cms-4.4.12
- dev-dependabot/composer/guzzlehttp/psr7-2.5.0
- dev-bugfix/contact-form-escape-HTML-104
This package is auto-updated.
Last update: 2024-09-15 03:44:40 UTC
README
此插件允许您向您的网站添加电子邮件联系表单。
要求
此插件需要Craft CMS 4.0.0+或5.0.0+。
安装
您可以从插件商店或使用Composer安装此插件。
从插件商店
转到项目的控制面板中的插件商店,搜索“Contact Form”。然后在其模态窗口中点击“安装”按钮。
使用Composer
打开您的终端并运行以下命令
# 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
用法
您的联系表单模板可能看起来像这样
{% macro errorList(errors) %} {% if errors %} {{ ul(errors, {class: 'errors'}) }} {% endif %} {% endmacro %} {% set submission = submission ?? null %} <form method="post" action="" accept-charset="UTF-8"> {{ csrfInput() }} {{ actionInput('contact-form/send') }} {{ redirectInput('contact/thanks') }} <h3><label for="from-name">Your Name</label></h3> {{ input('text', 'fromName', submission.fromName ?? '', { id: 'from-name', autocomplete: 'name', }) }} {{ submission ? _self.errorList(submission.getErrors('fromName')) }} <h3><label for="from-email">Your Email</label></h3> {{ input('email', 'fromEmail', submission.fromEmail ?? '', { id: 'from-email', autocomplete: 'email', }) }} {{ submission ? _self.errorList(submission.getErrors('fromEmail')) }} <h3><label for="subject">Subject</label></h3> {{ input('text', 'subject', submission.subject ?? '', { id: 'subject', }) }} {{ submission ? _self.errorList(submission.getErrors('subject')) }} <h3><label for="message">Message</label></h3> {{ tag('textarea', { text: submission.message ?? '', id: 'message', name: 'message', rows: 10, cols: 40, }) }} {{ submission ? _self.errorList(submission.getErrors('message')) }} <button type="submit">Send</button> </form>
唯一必填字段是 fromEmail
和 message
。其他所有内容都是可选的。
提交后重定向
如果您有一个隐藏的 redirect
输入,用户在成功发送电子邮件后将被重定向到它。以下变量可以用于您设置的URL/路径中
{fromName}
{fromEmail}
{subject}
例如,如果您想重定向到一个 contact/thanks
页面并将发送者的姓名传递给它,您可以设置输入如下
{{ redirectInput('contact/thanks?from={fromName}') }}
在您的 contact/thanks.html
模板中,您可以使用 craft.app.request.getQueryParam()
访问该 from
参数
<p>Thanks for sending that in, {{ craft.app.request.getQueryParam('from') }}!</p>
请注意,如果您没有包括一个 redirect
输入,当前页面将被重新加载。
显示闪存消息
当提交联系表单时,插件将在用户会话中设置一个 notice
(Craft 4)或 success
(Craft 5+)闪存消息。您可以在模板中这样显示它
{% 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 %}
添加额外字段
您可以通过将 message
字段拆分为多个字段,并使用数组语法为输入名称添加额外的字段到您的表单中
<h3><label for="message">Message</label></h3> <textarea rows="10" cols="40" id="message" name="message[body]">{{ submission.message.body ?? '' }}</textarea> <h3><label for="phone">Your phone number</label></h3> <input id="phone" type="text" name="message[Phone]" value=""> <h3>What services are you interested in?</h3> <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>
如果您有一个主要的“Message”字段,您应该将其命名为 message[body]
,就像在示例中那样。
使用上述表单发送的电子邮件可能会导致以下消息
• 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
默认情况下,没有对可以包含在 message
中的键的限制。您可以使用 config/contact-form.php
中的 allowedMessageFields
设置来限制允许的字段。
<?php return [ 'allowedMessageFields' => ['Phone', 'Services'], ];
覆盖插件设置
如果您在 config/
文件夹中创建一个名为 contact-form.php
的配置文件,您可以覆盖控制面板中的插件设置。由于该配置文件完全支持 多环境,这是在不同环境中拥有不同设置的一种便捷方式。
以下是一个配置文件的示例,以及您可以覆盖的所有可能值的列表。
<?php return [ 'toEmail' => 'bond@007.com', 'prependSubject' => '', 'prependSender' => '', 'allowAttachments' => false, 'successFlashMessage' => 'Message sent!' ];
动态添加电子邮件收件人
您可以通过在模板中添加一个名为 toEmail
的隐藏输入字段来从您的模板中以编程方式添加电子邮件收件人
<input type="hidden" name="toEmail" value="{{ 'me@example.com'|hash }}">
如果您想添加多个收件人,您可以提供一个以逗号分隔的电子邮件列表
<input type="hidden" name="toEmail" value="{{ 'me@example.com,me2@example.com'|hash }}">
然后从您的 config/contact-form.php
配置文件中,您需要添加一些逻辑
<?php $config = []; $request = Craft::$app->request; if ( !$request->getIsConsoleRequest() && ($toEmail = $request->getValidatedBodyParam('toEmail')) !== null ) { $config['toEmail'] = $toEmail; } return $config;
在此示例中,如果 toEmail
不存在或验证失败(被篡改),插件将回退到插件设置中定义的“收件人电子邮件”,因此您必须定义它。
文件附件
如果您希望您的联系表单接受文件附件,请按照以下步骤操作
- 前往控制面板中的设置 → 联系表单,确保插件已设置为允许附件。
- 确保您的开启HTML
<form>
标签包含enctype="multipart/form-data"
。 - 在您的表单中添加
<input type="file" name="attachment">
。 - 如果您想允许多个文件附件,请使用多个
<input type="file" name="attachment[]" multiple>
输入。
Ajax表单提交
如果您想通过Ajax提交联系表单,可以选择这样做。只需发送一个包含所有通常发送数据的POST请求到您的网站。
$('#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); } }); });
afterValidate
事件
当提交正在验证时,模块和插件可以通过在Submission
模型上使用afterValidate
事件来通知,提供它们自己的自定义验证逻辑。
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.'); } });
beforeSend
事件
模块和插件可以在使用beforeSend
事件通知发送消息给收件人之前收到通知。这也是将消息标记为垃圾邮件,防止其发送的机会。
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; } });
afterSend
事件
模块和插件可以在使用afterSend
事件通知发送消息给收件人之后收到通知。
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... });