aerni/livewire-forms

由 Laravel Livewire 驱动的 Statamic 表单框架

v9.3.2 2024-09-20 13:21 UTC

README

Statamic Packagist version Packagist Total Downloads

Livewire 表单

此插件提供了一款强大的框架,用于在 Laravel Livewire 中使用 Statamic 表单。不再需要使用 AJAX 提交表单或处理奇特的客户端验证库。Livewire Forms 是一款强大的工具,将使您的生活变得轻松许多!

特性

  • 使用 Statamic 表单模板作为表单构建器
  • 具有细粒度控制的实时验证
  • 无需客户端表单验证库
  • 验证规则只有一个来源
  • 使用 Google reCAPTCHA v2 和蜜罐字段进行垃圾邮件防护
  • 支持在表单模板中设置的显示条件
  • 多站点支持;翻译表单显示标签、说明、占位符等
  • 配置和样式化的表单视图

安装

使用 Composer 安装插件

composer require aerni/livewire-forms

发布包的配置(可选)

php please vendor:publish --tag=livewire-forms-config

手动捆绑 Livewire 和 Alpine

如果您正在 手动捆绑 Livewire 和 Alpine,您还需要导入 Livewire Forms 脚本

import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
import Clipboard from '@ryangjchandler/alpine-clipboard'
+ import "../../vendor/aerni/livewire-forms/resources/dist/js/livewire-forms";

Alpine.plugin(Clipboard)

Livewire.start()

然后,将 {{ livewire:styles }}{{ livewire:scriptConfig }} 标签添加到您的布局中

<html>
    <head>
        <!-- Antlers -->
        {{ livewire:styles }}

        <!-- Blade -->
        @livewireStyles
    </head>
    <body>
        <!-- Antlers -->
        {{ livewire:scriptConfig }}

        <!-- Blade -->
        @livewireScriptConfig
    </body>
</html>

此时,您可以安全地从您的表单视图中删除 livewire-forms.js 脚本,因为它现在包含在您的捆绑包中

- @assets
-     <script type="module" src="/vendor/livewire-forms/js/livewire-forms.js"></script>
- @endassets

命令

有一些有用的命令可以帮助您创建视图、主题和组件

入门指南

先决条件

此插件的视图使用 Tailwind CSS@tailwindcss/forms 进行样式设计。但是,您可以自由地更改视图。

运行设置命令

在控制台中运行 livewire-forms:setup 命令。它将引导您创建第一个 视图主题。您还可以创建一个 组件 以完全控制您的表单。

php please livewire-forms:setup

渲染表单

将 Livewire 表单组件添加到模板中,并提供 Statamic 表单的句柄。

<!-- Antlers -->
{{ livewire:form handle="contact" }}

<!-- Blade -->
<livewire:form handle="contact">

您还可以动态渲染通过 Statamic 的表单字段类型选择的表单

<!-- Antlers -->
{{ livewire:form :handle="field:handle" }}

<!-- Blade -->
<livewire:form :handle="field:handle">

如果您想使用与在 config/livewire-forms.php 中定义的默认值不同的视图或主题,请使用 viewtheme 参数。

<!-- Antlers -->
{{ livewire:form :handle="field:handle" view="contact" theme="regular" }}

<!-- Blade -->
<livewire:form :handle="field:handle" view="contact" theme="regular">

可用属性

视图

视图是您表单的入口点。您可以为每个表单使用相同的视图。

创建视图

使用 livewire-forms:view 命令创建新视图

php please livewire-forms:view

自动加载

视图通过表单的句柄自动加载。在下面的示例中,它将尝试加载 contact.blade.php 视图。如果不存在,则回退到在 config/livewire-forms.php 中定义的默认视图。

{{ livewire:form handle="contact" }}

Blade 指令

您可以在表单视图中使用一些 Blade 指令。这些指令了解表单的主题,并据此渲染视图。

自定义示例

有时您需要更多控制表单的标记。与其依赖表单的蓝图,您可能会选择完全自定义,并使用@formField指令渲染单个字段。

@formField('name')

您还可以使用数组作为第二个参数来添加或覆盖字段属性。

@formField('name', [
    'display' => 'Your Name',
    'tooltip' => 'Please enter your full name'
])

然后您可以访问字段视图中的属性。

{{ $field->display }}
{{ $field->tooltip }}

主题

主题允许您完全自定义每个单个表单视图。您可以有任何数量的主题。

创建主题

使用livewire-forms:theme命令创建一个新的主题

php please livewire-forms:theme

自动加载

主题通过表单的句柄自动加载。在下面的示例中,它将尝试加载contact主题的视图。如果该主题不存在,它将回退到在config/livewire-forms.php中定义的默认主题。如果所选主题的单个视图不存在,它将回退到该特定视图的默认主题。

{{ livewire:form handle="contact" }}

请注意:此插件的未来版本可能会对您的视图引入破坏性更改。在这种情况下,您必须根据更改手动更新您的视图。

字段视图

默认情况下,每个字段将根据其类型加载视图。例如,一个type: radiosubscription字段将加载radio.blade.php视图。

有时您可能想为特定字段加载不同的视图,例如选择订阅时使用一个花哨的单选按钮组。字段视图通过字段的句柄自动加载。在这个例子中,您只需在主题的fields文件夹下创建一个subscription.blade.php视图即可自动加载您的自定义视图。

您可以通过在蓝图中的字段配置中添加view: {视图名称}来手动覆盖字段的视图。

组件

有时您需要更多控制表单。例如,如果您想动态填充下拉字段的选项。有一些概念可以帮助您自定义表单体验。

创建组件

从创建一个新的组件开始。以下示例将在app/Livewire/ContactForm.php中创建一个新的表单组件。

php please livewire-forms:component ContactForm

自动加载

自定义组件通过将类名与表单的句柄匹配来自动加载。在下面的示例中,它将尝试加载App\Livewire\ContactForm.php组件。如果此组件不存在,它将回退到默认表单组件。

<!-- Antlers -->
{{ livewire:form handle="contact" }}

<!-- Blade -->
<livewire:form handle="contact">

注意:为了使自动加载魔法生效,组件的名称需要以Form结尾,例如ContactForm.php。

显式加载

您还可以通过名称显式加载自定义组件,就像加载任何其他Livewire组件一样。如果您需要向组件传递额外的自定义属性,则此操作是必要的。

<!-- Antlers -->
{{ livewire:contact-form my-custom-prop="value" }}

<!-- Blade -->
<livewire:contact-form my-custom-prop="value">

字段模型

每个Statamic字段类型都映射到一个Livewire Forms字段模型。模型负责生成字段的属性,如viewdisplayinstructionsoptions等。您可以在config/livewire-forms.php中找到默认映射。

例如,所有类型为\Statamic\Fieldtypes\Select::class的字段都绑定到\Aerni\LivewireForms\Fields\Select::class模型。为每个以Property结尾的模型方法创建一个字段属性,例如optionsProperty()将生成一个options属性。

要更改字段的默认模型,只需更改组件中的models属性的绑定。

protected array $models = [
    \Statamic\Fieldtypes\Select::class => \App\Fields\Select::class,
];

如果您只想更改特定字段的模型,只需使用字段的句柄作为键即可。

protected array $models = [
    'products' => \App\Fields\SelectProduct::class,
];

提示:您可以在config/livewire-forms.php中更改默认绑定。如果您有一个此插件不支持的字段类型,只需创建一个新的模型并将其绑定添加到配置中。

钩子

有几个钩子允许您在各个生命周期步骤修改字段和提交数据。

挂载字段

使用此钩子来修改字段在挂载之后。

public function mountedFields(Collection $fields): void
{
    $fields->get('name')->display('Your name');
}

表单提交

使用此钩子来修改在Statamic处理之前表单提交。

public function formSubmitted(Submission $submission): void
{
    $title = $submission->augmentedValue('entry')->value()->title;

    $submission->set('entry_title', $title);
}

事件

此插件派发了以下事件。

表单提交

在表单提交钩子之后立即触发 form-submitted Livewire 和 FormSubmitted Statamic 事件。您可以按照以下方式监听此事件。

Livewire

@script
<script>
    $wire.on('form-submitted', () => {
        //
    });
</script>
@endscript

Statamic Statamic\Events\FormSubmitted

public function handle(FormSubmitted $event)
{
    $event->submission; // The Submission object
}

自定义示例

在以下示例中,我们希望根据 Statamic 收集的条目动态生成选择字段的选项。我们还希望更改字段的视图,因为设计需要与常规选择字段不同。有两种方法可以实现我们的任务。我们可以创建一个 自定义字段模型 或使用 hydratedFields 回调。选择您感觉更好的路径。

使用自定义字段模型

我们首先创建一个新的 SelectProduct 字段模型类,该类继承自默认的 Select 模型类。然后我们覆盖 optionsProperty 方法以从集合中返回我们的选项。我们还使用 $view 类属性分配不同的视图。

namespace App\Fields;

use Aerni\LivewireForms\Fields\Select;
use Statamic\Facades\Entry;

class SelectProduct extends Select
{
    protected string $view = 'select_product';

    public function optionsProperty(): array
    {
        return Entry::whereCollection('products')
            ->mapWithKeys(fn ($product) => [$product->slug() => $product->get('title')])
            ->all();
    }
}

接下来,我们需要告诉表单我们想为哪个字段使用 SelectProduct 模型。在我们的例子中,我们只想为具有处理程序 products 的选择字段使用 SelectProduct 模型。

namespace App\Livewire;

use Aerni\LivewireForms\Livewire\Form;

class ContactForm extends Form
{
    protected array $models = [
        'products' => \App\Fields\SelectProduct::class,
    ];
}

使用 mountedFields 钩子

除了定义一个新的字段模型,我们还可以使用 mountedFields 钩子实现相同的效果。

namespace App\Livewire;

use Aerni\LivewireForms\Livewire\Form;

class ContactForm extends Form
{
    public function mountedFields(Collection $fields): void
    {
        $options = Entry::whereCollection('products')
            ->mapWithKeys(fn ($product) => [$product->slug() => $product->get('title')])
            ->all();

        $fields->get('products')
            ->options($options)
            ->view('select_product');
    }
}

渲染组件

最后,我们需要在模板中渲染我们的新 ContactForm 组件。

<!-- Antlers -->
{{ livewire:form handle="contact" }}

<!-- Blade -->
<livewire:form handle="contact">

验证

验证规则

您可以使用任何您想要的验证规则。只需将其添加到表单蓝图中的字段或使用 CP 中的蓝图构建器即可。

要针对其他字段的值进行验证,您需要像以下示例中那样获取其值

validate:
  - 'required_if:fields.newsletter.value,true'

实时验证

实时验证通过在 change 事件 上更新字段值来实现。您可以通过在字段的配置中设置 wire_model 参数来覆盖此行为。

tabs:
  main:
    display: Main
    sections:
      -
        fields:
          -
            handle: email
            field:
              type: text
              wire_model: live.debounce.150ms
              validate:
                - required
                - email

要使用 Livewire 的默认行为并在表单提交之前延迟所有网络请求,您可以将 wire_model: defer 设置。

验证消息

您可以通过创建一个 自定义表单组件 并使用以下两种方法之一来自定义字段的验证消息。

注意:确保在字段的处理程序前添加 data

使用 $messages 属性

protected $messages = [
    'fields.name.value.required' => 'What is your name, darling?',
];

使用 messages() 方法

protected function messages(): array
{
    return [
        'fields.name.value.required' => 'What is your name, darling?',
    ];
}

本地化

有几个默认的消息字符串,如 提交按钮标签成功消息,您可能想更改。您可以在全局或每个表单级别更改这些消息。

全局

发布语言文件并更改您想更改的任何消息

php artisan vendor:publish --tag=livewire-forms-translations

按表单

  1. 为每个本地化创建一个名为 livewire-forms.php 的文件,例如,resources/lang/en/livewire-forms.php
  2. 为要更改消息的每个表单创建一个包含其处理程序的数组。
  3. 使用与全局语言文件中相同的键。请注意,此文件中的消息将优先于全局语言文件中的消息。
return [

    'contact' => [
        'submit_button_label' => 'Contact now',
        'success_message' => 'Thanks for contacting us. We will be in touch.',
        'error_message' => 'There was an error with your submission:|There were :count errors with your submission:',
    ],

    'newsletter' => [
        'submit_button_label' => 'Signup now',
    ],

];

翻译部分和字段

您可以使用 JSON 文件翻译字段显示标签、说明、选项和占位符。为每种语言创建一个翻译文件,例如 resources/lang/de.json

示例

表单蓝图

tabs:
  main:
    display: Main
    sections:
      -
        display: Subscription
        instructions: 'Choose your subscription below'
        fields:
          -
            handle: subscription
            field:
              display: Subscription
              placeholder: 'Which subscription do you want?'

翻译文件

{
    "Subscription": "Abo",
    "Choose your subscription below": "Wähle dein Abo",
    "Which subscription do you want?": "Welches Abo möchtest du?",
}

验证字段类型

此插件附带了一个 Captcha 字段类型,允许您向表单添加 Google reCAPTCHA v2 (checkbox) 验证码。Captcha 字段类型在表单蓝图构建器中可用,就像任何其他字段类型一样。

注意:确保在您的 .env 文件中添加您的 captcha 密钥和密钥。

许可证

Livewire Forms 是一款 商业软件,但具有开源的代码库。如果您想在生产环境中使用它,您需要从 Statamic 市场购买许可证

Livewire Forms 不是 免费软件。

致谢

Michael Aerni 开发