@additionapps/polaris-form-builder 中文文档教程

发布于 3年前 浏览 4 项目主页 更新于 3年前

Polaris Form Builder

使用简单的配置对象在 Shopify Polaris 应用程序中构建表单。

此包使您能够在 Shopify 应用程序中构建复杂的表单,而无需加载混乱的模板样板。 只需将您想要在表单上的字段配置为纯 javascript 数组,表单生成器将负责显示字段和更新值。

它支持大多数开箱即用的基本 Polaris 表单字段组件,还可以处理自定义字段、分组字段、可重复字段和一些其他附加功能。 让我们开始吧!

Contents

Installation

您可以通过 NPM 安装此包:

npm install @additionapps/polaris-form-builder

请注意,此包要求您的应用程序使用 Shopify Polaris 版本 4.* 或更高版本。

Example usage

使用表单生成器是一个三步过程。

首先,配置您希望显示的表单。 这是一个包含字段对象的简单 javascript 数组:

// In MyForm.js
export const fields = [
    {
        key: "title",
        input: "text",
        config: {
            name: "title",
            label: "Product title",
            placeholder: "Product title",
        },
    },
    {
        key: "description",
        input: "text",
        config: {
            name: "description",
            label: "Product description",
            placeholder: "Product description",
        },
    },
];

接下来我们将定义我们的模型 - 我们希望表单与之交互的数据 - 以及设置此数据的方法。 我们将使用 React 功能组件作为示例:

// In MyComponent.jsx
export const MyComponent = () {
    const [model, setModel] = useState({
        title: null,
        description: null,
    });

    return (
        //...
    );
}

现在,剩下要做的就是配置我们的 Form Builder:

import { fields } from './MyForm';
import { PolarisFormBuilder} from '@additionapps/polaris-form-builder;

export const MyComponent = () {
    const [model, setModel] = useState({
        title: null,
        description: null,
    });

    return (
        <PolarisFormBuilder
            model={model}
            fields={fields}
            onModelUpdate={setModel}
        ></PolarisFormBuilder>
    );
}

就是这样! 表单生成器将负责显示您的表单字段,并在字段中的值发生变化时更新您的模型。 你可以在这里看到这个简单的例子:

href="https://codesandbox.io/s/simple-demo-fx8nq?file=/SimpleDemoForm.jsx">Polaris Form Builder - simple demo

Polaris Form Builder - 厨房水槽演示


Configuring a Form Builder

配置表单生成器时可用的选项比上面简单示例中显示的要多。 以下是可用的道具:

fields

必需。 包含要在表单上显示的每个字段的配置对象的数组。 请参阅定义字段

model

必需。 封装表单将与之交互的数据的对象。 此对象上的每个键都应对应于表单字段配置数组中某个字段的 key 属性。

onModelUpdate

必需。 当任何表单字段中的输入发生变化时,接受更新模型作为其唯一参数的函数。

units

可选。 包含与应在某些表单字段中使用的单位相关的配置的对象。 此对象中的键都是可选的,包括:

  • locale: The string representing the desired language as defined in BCP 47 . If not supplied, the locale will be automatically derived via navigator.language.
  • currency: The three-letter currency code as defined by ISO 4217]. If not supplied the currency will be derived automatically based on the locale.
  • weight: One of g (grams), kg (kilograms), oz (ounces) or lb (pounds).

errors

可选。 验证错误消息的对象。 该对象的键应该是错误所指字段的点符号路径,值是错误消息本身。 示例:

const errors = {
  'title' : 'The title field is required',
  'things.0.summary' => 'A thing must have a summary'
}

onErrorUpdate

可选。 接受更新的错误对象作为其唯一参数的函数。 当有错误的字段接收到新输入时,错误将从提供的 errors 对象中删除。 此回调函数允许消费组件对此更改做出反应。 有关详细信息,请参阅错误处理

focus

可选。 一个字符串,描述指向应关注的字段的点符号路径。 这在处理错误动态表单字段时很有用。

onFocusUpdate

可选。 一个函数,它接受一个字符串作为其唯一参数,该字符串描述最近关注的字段的点符号路径。 这在处理错误动态表单字段 时很有用。


Defining fields

传递给 Form Builder 的 fields 属性是一个对象数组,每个对象都配置表单中的一个字段。

所有字段对象至少应具有以下三个必需属性:

key - 与您传​​递给 Form Builder 的模型上的属性相匹配的字符串

input - 对应的字符串为内置字段类型之一或自定义字段类型(请参阅自定义字段)。 内置字段类型是:

  • checkbox
  • choice
  • group
  • money
  • percentage
  • range
  • repeater
  • select
  • text
  • weight

config - 允许您根据 Polaris 文档配置底层 Polaris 字段组件的对象。

所有字段也有一些可选键:

  • warning - accepts a string as a value. If this is present a yellow warning banner will display below the input with the string specified.
  • defaultValue - For use with subfields only. Accepts a string or number as a value.

某些字段需要指定其他选项。 各字段要求如下:

checkbox

该字段对应Shopify Polaris Checkbox字段。

最低配置:

{
  key: "my_checkbox_field",
  input: "checkbox",
  config: {
    // required by Polaris component
    label: "Do you agree?"
  }
}

config 对象可以包含 Shopify Polaris Checkbox 文档,除了 checkederroronChange,因为它们由 Form Builder 处理。

choice

此字段对应于 Shopify Polaris Choice List 字段。

最低配置:

{
  key: "my_checkbox_or_radio_list_field",
  input: "choice",
  config: {
    // required by Polaris component
    title: "Select some things",
    choices: [
      // { label: "Thing One", value: "one" },
      // { label: "Thing Two", value: "two" },
    ]
  }
}

config 对象可以包含 Shopify Polaris Choice List 文档,但 selectederroronChange 除外,因为它们由 Form Builder 处理。

group

group 字段是一个容器,可以并排显示两个或多个子字段。

最低配置:

{
    // The key for a group field does not correspond
  // to a property in your data model.  Prefixed here
  // with an underscore to make this more apparent
  key: "_my_group_field",
  input: "group",
  layout: 'condensed',
  subFields: [
    // Child field configuration objects
  ]
}

layout 键确定 group 应该使用压缩还是常规 Shopify Polaris 表单布局。 如果省略此键,将使用常规表单布局组。 如果该值设置为 condensed,将使用压缩形式布局组。

subFields 数组可以包含任何内置或自定义字段类型的配置对象。

money

该字段允许以货币的最低面额(例如美分、便士等)保留货币值。 通过将 units 对象传递给表单生成器来指定货币 - 请参阅配置表单生成器。

该值将显示为浮点数或整数 - 适用于货币 - 当字段获得焦点时,将显示基于区域设置的值的格式化表示(再次通过 units 指定)表单生成器上的道具)。

为了进行说明,我们假设一个 Form Builder 实例使用 GBP 作为货币,使用 en-GB 作为语言环境。 如果用户在货币字段中输入 10.45,则数据模型中保存的值将为 1045,并且在模糊时,该字段将显示 £10.45

最低配置:

{
  key: "my_money_field",
  input: "money",
  config: {
    // required by Polaris component
    label: "Price",
  }
}

config 对象可以包含 Shopify Polaris 文本字段中定义的任何道具 文档,除了 valueerrorfocusedonChangeonFocusonBlur,因为它们由 Form Builder 处理。

simple_money

该字段是 money 字段的更基本版本。 它本质上是一个带有前缀的 text 字段,显示 units 属性中指定的货币。 不对输入执行额外的检查或格式化 - 假设您的应用程序后端负责验证和处理输入,并且传递给该字段的值采用正确的格式。

最低配置:

{
  key: "my_simple_money_field",
  input: "simple_money",
  config: {
    // required by Polaris component
    label: "How much is it worth?",
  }
}

config 对象可以包含 Shopify Polaris 文本字段中定义的任何道具 文档,除了 valueerrorfocusedonFocusonChange因为这些是由 Form Builder 处理的。

percentage

该字段允许将百分比值保留为小数。 该值将在聚焦时显示为更人性化的百分比,并将显示基于语言环境的百分比的格式化版本(这是通过表单生成器上的 units 属性指定的 - 请参阅配置表单生成器)。

为了进行说明,我们假设一个 Form Builder 实例使用 en-GB 作为语言环境。 如果用户在百分比字段中输入 25,则数据模型中保存的值将为 0.25,并且在模糊时,该字段将显示 25 %

最低配置:

{
  key: "my_percentage_field",
  input: "percentage",
  config: {
    // required by Polaris component
    label: "What percentage?",
  }
}

config 对象可以包含 Shopify Polaris 文本字段中定义的任何道具 文档,除了 valueerrorfocusedonChangeonFocusonBlur,因为它们由 Form Builder 处理。

range_slider

此字段对应于 Shopify Polaris Range Slider 字段。

最低配置:

{
  key: "my_slider_field",
  input: "range_slider",
  config: {
    // required by Polaris component
    label: "What value?"
  }
}

config 对象可以包含 Shopify Polaris Range Slider 中定义的任何道具 文档,但 valueerroronChange 除外,因为它们由 Form Builder 处理。

repeater

repeater 字段使处理模型数据中的对象数组成为可能。 例如:

const data: {
  my_repeater_field: [
    { title: 'Foo', description: 'Bar' },
    { title: 'Baz', description: 'Qux' },
  ]
}

转发器字段将为用户提供添加和删除数据行的控件。

最低配置:

{
  key: "my_repeater_field",
  input: "repeater",
  emptyMessage: "No people added",
  addButtonText: "Add person",
  layout: 'stacked',
  title: 'My repeater field', //optional
  minRows: 1, //optional
  maxRows: 5, //optional
  subFields: [
    // Child field configuration objects
  ]
}

emptyMessage 属性是必需的,当转发器字段没有行时将显示。

addButtonText 属性确定显示在用于添加新行的按钮上的文本。 此属性是可选的 - 如果缺少该按钮将显示“添加行”。

title 属性将在转发器字段上方添加一个副标题。 此属性是可选的 - 如果缺少,则不会显示任何标题。

minRowsmaxRows 属性将确保转发器不能少于或多于指定的项目数。 一旦达到这些限制,将不会显示添加/删除按钮。 这些属性是可选的,可以独立设置。

layout 属性决定子字段的显示方式。 这可以是以下三个值之一:stackedgroupedcondensed。 这些选项对应于三个不同的 Shopify Polaris 表单布局 选项。 此属性是可选的 - 如果缺少布局将被堆叠

subFields 数组可以包含任何内置或自定义字段类型(包括其他转发器字段)的配置对象。

select

此字段对应于 Shopify Polaris 选择字段 字段。

最低配置:

{
  key: "my_select_field",
  input: "select",
  config: {
    // required by Polaris component
    label: "Choose a thing",
    options: [
      // { label: "Thing One", value: "one" },
      // { label: "Thing Two", value: "two" },
    ]
  }
}

config 对象可以包含 Shopify Polaris Select Field 文档,但 valueerroronChange 除外,因为它们由 Form Builder 处理。

simple_money

该字段是 money 字段的更基本版本。 它本质上是一个带有前缀的 text 字段,显示 units 属性中指定的货币。 不对输入执行额外的检查或格式化 - 假设您的应用程序后端负责验证和处理输入,并且传递给该字段的值采用正确的格式。

最低配置:

{
  key: "my_simple_money_field",
  input: "simple_money",
  config: {
    // required by Polaris component
    label: "How much is it worth?",
  }
}

config 对象可以包含 Shopify Polaris 文本字段中定义的任何道具 文档,除了 valueerrorfocusedonFocusonChange因为这些是由 Form Builder 处理的。

simple_weight

此字段是 weight 字段的更基本版本。 它本质上是一个 text 字段,带有一个后缀,显示 units 属性中指定的重量单位。 不对输入执行额外的检查或格式化 - 假设您的应用程序后端负责验证和处理输入,并且传递给该字段的值采用正确的格式。

最低配置:

{
  key: "my_simple_weight_field",
  input: "simple_weight",
  config: {
    // required by Polaris component
    label: "How much does it weigh?",
  }
}

config 对象可以包含 Shopify Polaris 文本字段中定义的任何道具 文档,除了 valueerrorfocusedonFocusonChange因为这些是由 Form Builder 处理的。

text

此字段对应于 Shopify Polaris 文本字段 字段。

最低配置:

{
  key: "my_text_field",
  input: "text",
  config: {
    // required by Polaris component
    label: "Choose a thing",
  }
}

config 对象可以包含 Shopify Polaris 文本字段中定义的任何道具 文档,除了 valueerrorfocusedonFocusonChange因为这些是由 Form Builder 处理的。

weight

该字段允许以克为单位保留重量值,同时让用户根据提供的重量单位输入值(这是通过表单生成器上的 units 属性指定的 - 请参阅配置表单生成器)。

为了说明,我们假设一个 Form Builder 实例使用 kg 作为重量单位。 如果用户在权重字段中输入 5,则数据模型中保存的值将为 5000。

最低配置:

{
  key: "my_weight_field",
  input: "weight",
  config: {
    // required by Polaris component
    label: "What weight?",
  }
}

config 对象可以包含 Shopify Polaris Text Field 文档,除了 valueerrorfocused< /code>、onChangeonFocusonBlur,因为它们由 Form Builder 处理。

Note for TypeScript users

内置字段从 Polaris 字段接口扩展而来。 因此,您应该确保为 config 对象中的底层 Polaris 字段提供所有 必需的道具。

在实践中,这通常意味着为您的字段提供一个 value(或者在类似选择的字段的情况下,您需要指定一个 selected 属性)。 通常您可以将其设置为 null - Form Builder 将在生成字段时覆盖它。 示例:

import Field from '@additionapps/polaris-form-builder;

const fields: Field[] = [
  {
    key: "my_text_field",
    input: "text",
    config: {
      // Both label and value are required
        // by Polaris component
      label: "Choose a thing",
      value: null
    }
  }
]

Error handling

Form Builder 可以负责显示通过 errors 属性传递给 PolarisFormBuilder 组件的表单验证错误。

通常有两种表单验证方法:

  • Validation on form submission - the server sends back a set of validation errors for the form which are then displayed to the user
  • Validation on input - the data model is checked as it is updated to ensure that it matches a set of validation requirements that are defined in JavaScript.

让我们看看表单构建器如何处理这些方法:

Validation on form submission

在提交表单时,您的应用程序通常会生成一个 XMLHttpRequest 并接收来自服务器的响应。 如果存在验证错误,这些错误将作为对象发回,然后可以将其传递到 Form Builder 实例中。

Form Builder 期望错误对象具有与您的数据模型中具有无效值的键相对应的键。 这些键应该使用点表示法来定位模型键,它们嵌套在数组中,例如:

const errors = {
  'title' : 'The title field is required',
  'things.0.summary' => 'A thing must have a summary'
}

当显示错误的字段接收到新输入时,Form Builder 实例将从错误对象中删除该项目。 为了保持父组件的状态与 Form Builder 同步,可以向 Form Builder 提供一个 onErrorUpdate 回调函数。 此方法将从 Form Builder 接收更新的错误对象,然后可以将其应用于父组件状态。

表单生成器还接受一个 focus 属性和一个 onFocusUpdate 回调方法。 此回调方法有助于确保在错误更新和表单构建器重新呈现时字段焦点不会丢失在文本(或类似文本)字段中。 这是一个示例:

Polaris Form Builder - 验证提交演示

注意 - 对于仅在表单提交时使用验证且不接受动态字段或动态单元的简单表单,无需使用这些事件回调来管理错误和焦点 - 表单生成器将在内部跟踪错误的更改。

Validation on input

为了方便您的用户,您可能希望在他们与您的表单交互时提供验证反馈。 表单生成器可以与对象验证器集成,例如流行的 Yup 库。

这是一个使用此库的简单示例,用于演示输入验证:

Polaris Form Builder - 输入演示验证

Dynamic fields

表单中的一个常见要求是字段根据用户的输入向用户呈现不同的选项或字段。 例如,如果用户在 country 字段中选择“United States”,他们应该会在 states 字段中看到美国各州的列表。 如果他们随后选择另一个 country,他们应该看到一组不同的 states

因为字段被定义为 JavaScript 数组,所以您可以在将其传递到 Form Builder 之前根据需要对其进行操作。 通常,这将涉及从您的模型中获取一个或多个值,并映射到您的表单配置中的字段,以根据这些值根据需要操作它们。

为了使这个过程更容易一些,您可以使用 transformFields 实用程序方法,该方法接受字段配置选项数组作为第一个参数,以及一个定义数组中每个字段应如何操作的回调。

如果 Form Builder 检测到传递给它的字段发生变化,它将重新呈现。

这是一个示例:

Polaris Form Builder - 动态字段演示< /a>

Custom fields

虽然内置字段类型将涵盖大多数用例,但在某些情况下可能需要自定义字段类型。

表单生成器接受可选的 customFields 道具。 这个 prop 应该传递一组功能性的 React 组件,每个组件都是一个自定义字段类型。

您可以在此处查看使用自定义字段类型的表单生成器示例:

Polaris Form Builder - 自定义字段演示

关于创建自定义字段的一些注意事项:

Naming

React 功能组件的名称应为 Pascal 大小写,并以单词 Field 为后缀。 在您的表单配置中定义字段时,将使用此名称的蛇形大小写形式(不带字段后缀)。 例如,如果您的自定义字段组件是 CustomColourField,您应该在表单配置中将此字段类型称为 input: 'custom_colour'

Props

您的字段应该接受四个属性 - fieldstateactionsancestors

  • field - the configuration object for the field, as defined in your form config.
  • state - an object representing the current internal state of the Form Builder instance. There are several properties on this object:
    • model - the current state of the model, passed into the Form Builder.
    • fields - the full form config object.
    • errors - the current state of any errors passed into the Form Builder.
    • focus - a dot notation path for the most recently focused field.
    • inputs - an array of input types currently registered on the current Form Builder instance. This will include all the built-in field types and any custom fields passed into the form builder.
    • units - an object with information about the units that should be used to display certain field values.
  • actions - an object holding a number of methods used to manage the state of the form builder. Relevant methods:
    • updateField(value, field, ancestors) - used to update the model with the new value. This method is typically invoked when the field receives input.
    • setFocus(field, ancestors) - used to keep track of the most recently focused form field. This is typically used for text-like fields and in usually invoked on field focus.
  • ancestors - an array of ‘field parent’ objects that helps to determine the position of a field within the model. This value typically won’t be interacted with directly but will be passed to actions like updateField and setFocus

Examples

本自述文件包含许多实时为方便起见再次在下面列出的示例:


Changelog

请参阅 CHANGELOG 了解更多信息最近发生了什么变化。

Contributing

有关详细信息,请参阅CONTRIBUTING

Security

如果您发现任何与安全相关的问题,请发送电子邮件至 john@addition.com.au 而不是使用问题跟踪器。

Treeware

您可以自由使用此包,但如果它适用于您的生产环境,我们将非常感谢您为世界购买或种植一棵树。

现在众所周知,应对气候危机和防止气温上升超过 1.5 摄氏度的最佳工具之一是植树。 如果您为我的森林做出贡献,您将为当地家庭创造就业机会并恢复野生动物栖息地。

您可以在 Offset Earth 购买树木 在 Treeware

阅读更多关于 Treeware 的信息a>

Credits

约翰·威尔斯 所有贡献者

License

MIT 许可证 (MIT)。 请参阅许可证文件文件以获取更多信息。

Polaris Form Builder

Build forms in your Shopify Polaris apps with a simple config object.

This package enables you to build complex forms in your Shopify applications without a load of messy template boilerplate. Simply configure the fields you want on your form as a plain javascript array and the Form Builder will take care of displaying the fields and updating the values.

It supports most of the basic Polaris form field components out of the box and also handles custom fields, grouped fields, repeatable fields and a few other bells and whistles. Let’s dig in!

Contents

Installation

You can install this package via NPM:

npm install @additionapps/polaris-form-builder

Note that this package requires that your application is using Shopify Polaris version 4.* or higher.

Example usage

Using the form builder is a three step process.

First, configure the form that you wish to display. This is a simple javascript array containing field objects:

// In MyForm.js
export const fields = [
    {
        key: "title",
        input: "text",
        config: {
            name: "title",
            label: "Product title",
            placeholder: "Product title",
        },
    },
    {
        key: "description",
        input: "text",
        config: {
            name: "description",
            label: "Product description",
            placeholder: "Product description",
        },
    },
];

Next we’ll define our model - the data that we want the form to interact with - along with a method to set this data. We’ll use a React functional component as an example:

// In MyComponent.jsx
export const MyComponent = () {
    const [model, setModel] = useState({
        title: null,
        description: null,
    });

    return (
        //...
    );
}

Now, all that’s left to do is to configure our Form Builder:

import { fields } from './MyForm';
import { PolarisFormBuilder} from '@additionapps/polaris-form-builder;

export const MyComponent = () {
    const [model, setModel] = useState({
        title: null,
        description: null,
    });

    return (
        <PolarisFormBuilder
            model={model}
            fields={fields}
            onModelUpdate={setModel}
        ></PolarisFormBuilder>
    );
}

That’s it! The form builder will take care of displaying your form fields and will update your model when the values in the fields change. You can see this simple example in action here:

Polaris Form Builder - simple demo

A more advanced ‘kitchen sink’ demo showing all built-in field types, a custom field and dynamic fields can be seen here:

Polaris Form Builder - kitchen sink demo


Configuring a Form Builder

There are more options available when configuring a form builder than are shown in the simple example above. Here are the available props:

fields

Required. An array containing configuration objects for each field you want to display on your form. See Defining Fields.

model

Required. An object that encapsulates the data that the form will interact with. Each key on this object should correspond to the key property for a field in your form field config array.

onModelUpdate

Required. A function that accepts as its only parameter the updated model when the input in any of the form’s fields changes.

units

Optional. An object containing configuration relating to the units that should be used in certain form fields. The keys in this object are all optional and include:

  • locale: The string representing the desired language as defined in BCP 47 . If not supplied, the locale will be automatically derived via navigator.language.
  • currency: The three-letter currency code as defined by ISO 4217]. If not supplied the currency will be derived automatically based on the locale.
  • weight: One of g (grams), kg (kilograms), oz (ounces) or lb (pounds).

errors

Optional. An object of validation error messages. The keys of this object are expected to be the dot notation paths of the field the error refers to and the values are the error messages themselves. Example:

const errors = {
  'title' : 'The title field is required',
  'things.0.summary' => 'A thing must have a summary'
}

onErrorUpdate

Optional. A function that accepts as its only parameter the updated errors object. When a field with an error receives new input, the error is removed from the supplied errors object. This callback function allows the consuming component to react to this change. For more information see Error handling.

focus

Optional. A string describing a dot notation path to the field that should be focused. This is useful when working with errors or dynamic form fieldss.

onFocusUpdate

Optional. A function that accepts as its only parameter a string describing the dot notation path of the field that was most recently focused. This is useful when working with errors or dynamic form fields.


Defining fields

The fields prop passed to the Form Builder is an array of objects, each one configuring a single field in your form.

All field objects should at minimum have the following three required properties:

key - a string that matches the property on the model you pass to the Form Builder

input - a string that corresponds to one of the built-in field types or a custom field type (see Custom fields). The built in field types are:

  • checkbox
  • choice
  • group
  • money
  • percentage
  • range
  • repeater
  • select
  • text
  • weight

config - an object allowing you to configure the underlying Polaris field component per the Polaris documentation.

All fields also have some optional keys:

  • warning - accepts a string as a value. If this is present a yellow warning banner will display below the input with the string specified.
  • defaultValue - For use with subfields only. Accepts a string or number as a value.

Certain fields require additional options to be specified. The requirements for each field are as follows:

checkbox

This field corresponds to the Shopify Polaris Checkbox field.

Minimum configuration:

{
  key: "my_checkbox_field",
  input: "checkbox",
  config: {
    // required by Polaris component
    label: "Do you agree?"
  }
}

The config object can include any of the props defined in the Shopify Polaris Checkbox documentation except checked, error and onChange as these are handled by the Form Builder.

choice

This field corresponds to the Shopify Polaris Choice List field.

Minimum configuration:

{
  key: "my_checkbox_or_radio_list_field",
  input: "choice",
  config: {
    // required by Polaris component
    title: "Select some things",
    choices: [
      // { label: "Thing One", value: "one" },
      // { label: "Thing Two", value: "two" },
    ]
  }
}

The config object can include any of the props defined in the Shopify Polaris Choice List documentation except selected, error and onChange as these are handled by the Form Builder.

group

A group field is a container that enables the display of two or more sub fields side by side.

Minimum configuration:

{
    // The key for a group field does not correspond
  // to a property in your data model.  Prefixed here
  // with an underscore to make this more apparent
  key: "_my_group_field",
  input: "group",
  layout: 'condensed',
  subFields: [
    // Child field configuration objects
  ]
}

The layout key determines if the group should use a condensed or regular Shopify Polaris Form Layout. If this key is omitted a regular form layout group will be used. If the value is set to condensed a condensed form layout group will be used.

The subFields array can include configuration objects for any of the built in or custom field types.

money

This field allows for monetary values to be persisted in the lowest denomination (e.g. cents, pence etc) for the currency. Currency is specified by passing in a units object to the Form Builder - see Configuring a Form Builder.

The value will be displayed as a float or integer - as appropriate for the currency - when the field is focused and will display a formatted representation of the value based on the locale (again this is specified via the units prop on the Form Builder).

To illustrate, let’s assume a Form Builder instance is using GBP as currency and en-GB as a locale. If the user enters 10.45 into a money field, the value saved on the data model will be 1045 and on blur, the field will display £10.45.

Minimum configuration:

{
  key: "my_money_field",
  input: "money",
  config: {
    // required by Polaris component
    label: "Price",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onChange, onFocus and onBlur as these are handled by the Form Builder.

simple_money

This field is a much more basic version of the money field. It is essentially a text field with a prefix displaying the currency specified in the units prop. No additional checks or formatting are performed on input - it is assumed that the backend of your application is responsible for validating and processing input and that the value passed to this field is in the correct format.

Minimum configuration:

{
  key: "my_simple_money_field",
  input: "simple_money",
  config: {
    // required by Polaris component
    label: "How much is it worth?",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onFocus and onChange as these are handled by the Form Builder.

percentage

This field allows for percentage values to be persisted as a decimal. The value will be displayed as the more human-friendly percentage when focussed and will display a formatted version of the percentage based on the locale (This is specified via the units prop on the Form Builder - see Configuring a Form Builder).

To illustrate, let’s assume a Form Builder instance is using en-GB as a locale. If the user enters 25 into a percentage field, the value saved on the data model will be 0.25 and on blur, the field will display 25 %.

Minimum configuration:

{
  key: "my_percentage_field",
  input: "percentage",
  config: {
    // required by Polaris component
    label: "What percentage?",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onChange, onFocus and onBlur as these are handled by the Form Builder.

range_slider

This field corresponds to the Shopify Polaris Range Slider field.

Minimum configuration:

{
  key: "my_slider_field",
  input: "range_slider",
  config: {
    // required by Polaris component
    label: "What value?"
  }
}

The config object can include any of the props defined in the Shopify Polaris Range Slider documentation except value, error and onChange as these are handled by the Form Builder.

repeater

A repeater field makes it possible to work with arrays of objects in model data. For example:

const data: {
  my_repeater_field: [
    { title: 'Foo', description: 'Bar' },
    { title: 'Baz', description: 'Qux' },
  ]
}

A repeater field will offer the user controls for adding and deleting rows of data.

Minimum configuration:

{
  key: "my_repeater_field",
  input: "repeater",
  emptyMessage: "No people added",
  addButtonText: "Add person",
  layout: 'stacked',
  title: 'My repeater field', //optional
  minRows: 1, //optional
  maxRows: 5, //optional
  subFields: [
    // Child field configuration objects
  ]
}

The emptyMessage property is required and will be displayed when the repeater field has no rows.

The addButtonText property determines the text that is displayed on the button used to add new rows. This property is optional - if missing the button will display ‘Add row’.

The title property will add a subheading above the repeater fields. This property is optional - if missing no title will be displayed.

The minRows and maxRows properties will ensure that the repeater cannot have less than or more than the number of items specified. The add/remove buttons will not be displayed once these limits are reached. These properties is optional and can be set independently.

The layout property determines how the child fields will be displayed. This can be one of three values: stacked, grouped or condensed. The choices correspond to the three different Shopify Polaris Form Layout options. This property is optional - if missing the layout will be stacked.

The subFields array can include configuration objects for any of the built in or custom field types (including other repeater fields).

select

This field corresponds to the Shopify Polaris Select Field field.

Minimum configuration:

{
  key: "my_select_field",
  input: "select",
  config: {
    // required by Polaris component
    label: "Choose a thing",
    options: [
      // { label: "Thing One", value: "one" },
      // { label: "Thing Two", value: "two" },
    ]
  }
}

The config object can include any of the props defined in the Shopify Polaris Select Field documentation except value, error and onChange as these are handled by the Form Builder.

simple_money

This field is a much more basic version of the money field. It is essentially a text field with a prefix displaying the currency specified in the units prop. No additional checks or formatting are performed on input - it is assumed that the backend of your application is responsible for validating and processing input and that the value passed to this field is in the correct format.

Minimum configuration:

{
  key: "my_simple_money_field",
  input: "simple_money",
  config: {
    // required by Polaris component
    label: "How much is it worth?",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onFocus and onChange as these are handled by the Form Builder.

simple_weight

This field is a much more basic version of the weight field. It is essentially a text field with a suffix displaying the weight units specified in the units prop. No additional checks or formatting are performed on input - it is assumed that the backend of your application is responsible for validating and processing input and that the value passed to this field is in the correct format.

Minimum configuration:

{
  key: "my_simple_weight_field",
  input: "simple_weight",
  config: {
    // required by Polaris component
    label: "How much does it weigh?",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onFocus and onChange as these are handled by the Form Builder.

text

This field corresponds to the Shopify Polaris Text Field field.

Minimum configuration:

{
  key: "my_text_field",
  input: "text",
  config: {
    // required by Polaris component
    label: "Choose a thing",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onFocus and onChange as these are handled by the Form Builder.

weight

This field allows for weight values to be persisted in grams whilst letting the user enter values based on the provided weight unit (this is specified via the units prop on the Form Builder - see Configuring a form builder).

To illustrate, let’s assume a Form Builder instance is using kg as the weight unit. If the user enters 5 into a weight field, the value saved on the data model will be 5000.

Minimum configuration:

{
  key: "my_weight_field",
  input: "weight",
  config: {
    // required by Polaris component
    label: "What weight?",
  }
}

The config object can include any of the props defined in the Shopify Polaris Text Field documentation except value, error, focused, onChange, onFocus and onBlur as these are handled by the Form Builder.

Note for TypeScript users

The built-in fields extend from the Polaris field interfaces. As as result you should ensure that you supply all required props for the underlying Polaris field in your config object.

In practice that will often mean supplying a value (or in the case of choice-like fields you will need to specify a selected property) for your field. Generally you can just set this to null - the Form Builder will overwrite this when generating the field. Example:

import Field from '@additionapps/polaris-form-builder;

const fields: Field[] = [
  {
    key: "my_text_field",
    input: "text",
    config: {
      // Both label and value are required
        // by Polaris component
      label: "Choose a thing",
      value: null
    }
  }
]

Error handling

The Form Builder can take care of displaying form validation errors that are passed to the PolarisFormBuilder component via the errors prop.

Typically there are two approaches to form validation:

  • Validation on form submission - the server sends back a set of validation errors for the form which are then displayed to the user
  • Validation on input - the data model is checked as it is updated to ensure that it matches a set of validation requirements that are defined in JavaScript.

Let’s look at how the Form Builder handles these approaches:

Validation on form submission

On form submission, your application will typically make an XMLHttpRequest and receive a response back from the server. If there are validation errors these will be sent back as an object which can then be passed into the Form Builder instance.

The Form Builder expects the error object to have keys that correspond to the key on your data model that has an invalid value. These keys should use dot notation to target model keys are are nested within arrays e.g.:

const errors = {
  'title' : 'The title field is required',
  'things.0.summary' => 'A thing must have a summary'
}

When a field that is is displaying an error receives new input, the Form Builder instance will remove that item from the errors object. In order to keep the state of the parent component in sync with the Form Builder, an onErrorUpdate callback function can be supplied to the Form Builder. This method will receive the updated errors object from the Form Builder which can then be applied to the parent component state.

The form builder also accepts a focus prop and an onFocusUpdate callback method. This callback method helps to ensure that field focus is not lost in text (or text-like) fields when errors update and the form builder re-renders. Here is an example:

Polaris Form Builder - validation on submit demo

Note - for simple forms that only use validation on form submission and do not accept dynamic fields or dynamic units, managing errors and focus using these event callbacks is not necessary - the Form Builder will track changes to the errors internally.

Validation on input

As a convenience for your users you may want to provide validation feedback as they interact with your form. The Form Builder can be integrated with object validators such as the popular Yup library.

Here is a simple example using this library that demonstrates on-input validation:

Polaris Form Builder - validation on input demo

Dynamic fields

A common requirement in forms is for fields to present the user with different options or fields based on their input. For example if a user selects “United States” in a country field they should see a list of US states in a states field. If they then select another country they should see a different set of states.

Because fields are defined as a JavaScript array you can manipulate it however you need to before passing it into the Form Builder. Typically, this will involve taking one or more values from your model and the mapping over the fields in your form config to manipulate them as required based on those values.

To make this process a little easier, you can use the transformFields utility method which accepts the array of field config options as it’s first argument and a callback that defines how each field in the array should be manipulated.

If the Form Builder detects a change in the fields it has been passed it will re-render.

Here is an example:

Polaris Form Builder - dynamic fields demo

Custom fields

Whilst the built-in field types will cover the majority of use-cases, there may be occasions where a custom field type is required.

The Form Builder accepts an optional customFields prop. This prop should be passed an array of functional React components, each one of which is a custom field type.

You can see an example of a Form Builder using a custom field type here:

Polaris Form Builder - custom fields demo

A few notes on creating custom fields:

Naming

The name of the React functional component should be pascal case and be suffixed with the word Field. The snake case form of this name (without the field suffix) will be used when defining the field in your form config. For example if your custom field component is CustomColourField you should refer to this field type in your form config as input: 'custom_colour'.

Props

Your field should accept four props - field, state, actions and ancestors:

  • field - the configuration object for the field, as defined in your form config.
  • state - an object representing the current internal state of the Form Builder instance. There are several properties on this object:
    • model - the current state of the model, passed into the Form Builder.
    • fields - the full form config object.
    • errors - the current state of any errors passed into the Form Builder.
    • focus - a dot notation path for the most recently focused field.
    • inputs - an array of input types currently registered on the current Form Builder instance. This will include all the built-in field types and any custom fields passed into the form builder.
    • units - an object with information about the units that should be used to display certain field values.
  • actions - an object holding a number of methods used to manage the state of the form builder. Relevant methods:
    • updateField(value, field, ancestors) - used to update the model with the new value. This method is typically invoked when the field receives input.
    • setFocus(field, ancestors) - used to keep track of the most recently focused form field. This is typically used for text-like fields and in usually invoked on field focus.
  • ancestors - an array of ‘field parent’ objects that helps to determine the position of a field within the model. This value typically won’t be interacted with directly but will be passed to actions like updateField and setFocus

Examples

This readme contains a number of live examples which are listed again below for convenience:


Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email john@addition.com.au instead of using the issue tracker.

Treeware

You’re free to use this package, but if it makes it to your production environment we would highly appreciate you buying or planting the world a tree.

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you contribute to my forest you’ll be creating employment for local families and restoring wildlife habitats.

You can buy trees at Offset Earth

Read more about Treeware at Treeware

Credits

John Wyles All Contributors

License

The MIT License (MIT). Please see License File File for more information.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文