Forms


Note

The content for this page requires a major update. The legacy page contains outdated and potentially inaccurate information. You can still access it in the Mautic Developer Documentation archived repository.

If you’re interested in helping develop the new content for this page and others, consider joining the documentation efforts.

Please read the Contributing Guidelines and Contributing to Mautic’s documentation to get started.

You can extend Forms by listening to the \Mautic\FormBundle\FormEvents::FORM_ON_BUILD event. Read more about listeners and subscribers. At the bottom of this document, you can find code examples to make it easier to get started.

Form Fields

To add a custom Form Field, use the $event->addFormField($identifier, $parameters) method. $identifier must be something unique. The $parameters array can contain the following elements:

Key

Required

Type

Description

label

Required

string

The language string for the option in the dropdown

formType

Required

string

The alias of a custom Form type used to set config options

template

Required

string

View template used to render the formType, for example HelloWorldBundle:SubscribedEvents\FormField:customfield.html.php

help

Optional

string

The language string for providing a help text below the form element.

formTypeOptions

Optional

array

Array of options to include into the formType’s $options argument

formTypeCleanMasks

Optional

array

Array of input masks to clean a values from formType

formTypeTheme

Optional

array

Array of input masks to clean a values from formType

valueFilter

Optional

mixed

Filter to use to clean the submitted value as supported by InputHelper or a callback function that accepts the arguments \Mautic\FormBundle\Entity\Field $field and $value.

valueConstraints

Optional

mixed

Callback function to use to validate the value; the function should accept the arguments \Mautic\FormBundle\Entity\Field $field and $filteredValue.

builderOptions

Optional

array

Array of boolean options for the Form builder:

<?php

$builderOptions = [
    'addHelpMessage' => true,
    'addShowLabel' => true,
    'addDefaultValue' => true,
    'addLabelAttributes' => true,
    'addInputAttributes' => true,
    'addIsRequired' => true
];

表单提交操作

要添加一个操作,使用 ‘$event->addSubmitAction($identifier, $parameters)’ 方法。 $identifier 必须是唯一的标识符。 $parameters 数组可以包含以下元素:

Key

Required

Type

Description

label

Required

string

下拉菜单中选项的语言字符串。

eventName

Required

string

这是用于处理此操作的自定义事件名称。它接收一个 SubmissionEvent 对象。

description

Optional

string

用于选项工具提示的语言字符串。

formType

Optional

string

自定义表单类型的别名,用于设置配置选项。

formTypeOptions

Optional

array

包含在 formType$options 参数中的选项数组。

formTypeCleanMasks

Optional

array

用于清理来自 formType 的值的输入掩码数组。

formTypeTheme

Optional

string

用于自定义 formType 元素的的主题。

template

Optional

string

用于渲染 formType 的视图模板。

注册以监听 eventName 的订阅者将获得一个 MauticFormBundleEventsSubmissionEvent 实例,其中包含有关提交的详细信息。

有时,需要在所有其他提交操作完成后执行某些操作,例如重定向到另一个 URL。 为此,通过处理该操作的订阅者注册一个提交回调。 您可以在那时使用 $event->setPostSubmitCallbackResponse($identifier, $response) 注入 SymfonyComponentHttpFoundationResponse 对象,或者使用 $event->setPostSubmitCallback($key, [‘eventName’ => HelloWorld::ANOTHER_CUSTOM_EVENT]) 注册另一个自定义事件,以便在所有提交操作完成后触发该事件。

表单验证

要添加自定义验证,请使用 ‘$event->addValidator($identifier, $parameters)’ 方法。 $identifier 必须是唯一的标识符。 $parameters 数组可以包含以下元素:

Key

Required

Type

Description

eventName

Required

string

用于验证表单或特定字段的自定义事件名称。

fieldType

Optional

string

自定义表单类型的键,例如通过 addFormField() 注册的类型,用于限制此监听器。否则,每个字段都会发送到监听器。

formType

Optional

string

用于为“validator”选项卡生成附加字段的表单类型类。

The listener for the Form event receives a Mautic\FormBundle\Event\ValidationEvent object. Obtain the field with $event->getField();, do the logic to fail a validation, then execute $event->failedValidation('I said so.');.

Example code

<?php
// plugins/HelloWorldBundle/EventListener/FormSubscriber.php

declare(strict_types=1);

namespace MauticPlugin\HelloWorldBundle\EventListener;

use MauticPlugin\HelloWorldBundle\HelloWorldEvents;
use Mautic\FormBundle\Event\FormBuilderEvent;
use Mautic\FormBundle\Event\SubmissionEvent;
use Mautic\FormBundle\Event\ValidationEvent;
use Mautic\FormBundle\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

class FormSubscriber implements EventSubscriberInterface
{
    /**
    * {@inheritdoc}
    */
    static public function getSubscribedEvents()
    {
        return [
            FormEvents::FORM_ON_BUILD                         => ['onFormBuilder', 0],
            // Generic validation function that runs on ALL field types
            FormEvents::ON_FORM_VALIDATE                      => ['onFormValidate', 0],
            HelloWorldEvents::ON_FORM_SUBMISSION              => ['onFormSubmission', 0],
            // Only validates our custom field type (helloworld.customfield)
            HelloWorldEvents::ON_FORM_CUSTOM_FIELD_VALIDATION => ['onFormValidateCustomFIeld', 0]
        ];
    }

    /**
    * Add a simple email form
    */
    public function onFormBuilder(FormBuilderEvent $event): void
    {
        // Register a custom form field
        $event->addFormField(
            'helloworld.customfield',
            [
                // Field label
                'label'    => 'plugin.helloworld.formfield.customfield',

                // Form service for the field's configuration
                'formType' => 'helloworld_worlds',

                // Template to use to render the formType
                'template' => 'HelloWorldBundle:SubscribedEvents\FormField:customfield.html.php'
            ]
        );
// 注册表单提交操作
$event->addSubmitAction(

‘helloworld.sendemail’, [

// 在下拉列表中分组的标签 ‘group’ => ‘plugin.helloworld.header’,

// 在下拉列表中显示的标签 ‘label’ => ‘plugin.helloworld.formaction.send_email’, ‘description’ => ‘plugin.helloworld.formaction.send_email_descr’,

// 用于自定义配置选项的表单服务 ‘formType’ => ‘helloworld_worlds’, ‘formTheme’ => ‘HelloWorldBundle:FormThemeSubmitAction’,

// 提交后执行的回调方法 ‘eventName’ => HelloWorldEvents::ON_FORM_SUBMISSION

]

);

/** * 注册自定义验证服务。这仅在以下情况下需要: * - 您只想验证您的自定义字段类型(通用的 FormEvents::ON_FORM_VALIDATE 会针对所有字段类型运行,效率较低) * - 您有更复杂的验证逻辑,希望将其放在单独的事件监听器中 * * 在其他情况下,您可以简单地监听 FormEvents::ON_FORM_VALIDATE,如下面的 onFormValidate() 方法所示。 */ $event->addValidator(

‘helloworld.customfield’, [

‘eventName’ => HelloWorldEvents::ON_FORM_CUSTOM_FIELD_VALIDATION, // 可选 - 否则所有字段都将通过此监听器进行验证 ‘fieldType’ => ‘helloworld.customfield’, // 可选 - 否则仅会生成默认的“required”选项到验证标签 ‘formType’ => MauticPluginHelloWorldBundleFormTypeHelloWorldType::class

]

);

}

/** * 通用的验证函数,适用于所有字段类型。 * 由于效率原因,如果只需要验证自定义字段类型,建议设置自定义验证器(参见上面的 $event->addValidator())。 */ public function onFormValidate(ValidationEvent $event): void {

$field = $event->getField(); $validation = $field->getValidation();

if ($field->getType() === ‘helloworld.customfield’ && !empty($validation[‘c_enable’])) {
if (empty($validation[‘helloworld_customfield_enable_validationmsg’])) {

$event->failedValidation($validation[‘helloworld_customfield_enable_validationmsg’]);

} else {

$event->failedValidation(‘plugin.helloworld.formfield.customfield.invalid’);

}

}

}

/**
  • Validation function that we registered specifically for our custom field type (helloworld.customfield).

  • We don’t need to check the field in this case, because it’ll only trigger when validating our custom field

  • (see $event->addValidator() above).

*/ public function onFormValidateCustomField(ValidationEvent $event): void {

$field = $event->getField(); $validation = $field->getValidation();

if (!empty($validation[‘c_enable’])) {
if (empty($validation[‘helloworld_customfield_enable_validationmsg’])) {

$event->failedValidation($$validation[‘helloworld_customfield_enable_validationmsg’]);

} else {

$event->failedValidation(‘plugin.helloworld.formfield.customfield.invalid’);

}

}

}

public function onFormSubmission(SubmissionEvent $event): void {

// Get the submitted data $data = $event->getPost();

// Redirect to an external URL after the form has been submitted $event->setPostSubmitCallbackResponse(‘helloworld.submit.response’, new RedirectResponse(’https://mydomain.com’));

// Dispatch a custom event to be dispatched after all submit actions have been processed $event->setPostSubmitCallback(‘helloworld.submit.callback’, [

‘eventName’ => HelloWorldEvents::ON_FORM_SUBMISSION_CALLBACK

]);

}

}

<?php

namespace MauticPlugin\HelloWorldBundle;

final class HelloWorldEvents
{
    /**
    * The plugin.hello.world.on_form_submission event is fired when a form is submitted.
    *
    * The event listener receives a Mautic\FormBundle\Events\SubmissionEvent
    *
    * @var string
    */
    public const ON_FORM_SUBMISSION = 'plugin.hello.world.on_form_submission';

    /**
    * The plugin.hello.world.on_form_submission_callback event is fired after all submit actions have been processed
    *
    * The event listener receives a Mautic\FormBundle\Events\SubmissionEvent
    *
    * @var string
    */
    public const ON_FORM_SUBMISSION_CALLBACK = 'plugin.hello.world.on_form_submission_callback';

    /**
    * The plugin.hello.world.on_form_validation event is fired when our custom field type (helloworld.customfield)
    * is being validated in a form submission.
    *
    * The event listener receives a Mautic\FormBundle\Event\ValidationEvent
    *
    * @var string
    */
    public const ON_FORM_CUSTOM_FIELD_VALIDATION = 'plugin.hello.world.on_form_custom_field_validation';
}