跳转到主要内容

FormKit

基本用法

FormKit 将单个组件作为其公开 API 暴露出来:<Form />。所有其他元素以上下文组件、修饰符或纯数据的形式产出。

每个表单由一个或多个字段组成,字段表示某个控件(control)的值、验证和元数据。每个字段封装一个控件,控件是用户与之交互以输入数据的表单元素,例如输入框或选择框。控件类型通过字段上的 @type 指定。还提供了其他实用组件,例如 submit 或 alert。

下面是一个最基本的表单示例:

import Component from "@glimmer/component";
import { action } from "@ember/object";
import Form from "discourse/components/form";

export default class MyForm extends Component {
  @action
  handleSubmit(data) {
    // do something with data
  }

  <template>
    <Form @onSubmit={{this.handleSubmit}} as |form|>
      <form.Field
        @name="username"
        @title="Username"
        @validation="required"
        @type="input"
        as |field|
      >
        <field.Control />
      </form.Field>

      <form.Field @name="age" @title="Age" @type="input-number" as |field|>
        <field.Control />
      </form.Field>

      <form.Submit />
    </Form>
  </template>
}

表单

产出的参数

form

Form 组件会产出一个 form 对象,其中包含上下文组件和辅助函数。

常用成员包括:

  • Field、Object、Collection、Fieldset、Row、Section、Container
  • Submit、Reset、Button、Alert、Actions
  • CheckboxGroup、InputGroup、ConditionalContent
  • set(name, value)、setProperties(object)、addItemToCollection(name, value)

示例

<Form as |form|>
  <form.Row as |row|>
    <!-- ... -->
  </form.Row>
</Form>

transientData

transientData 是表单当前的草稿状态。它以 @data 的副本开始,随用户编辑字段而更新,并且不会修改原始的 @data 对象。

:information_source: 如果你希望表单中的条件判断基于其他字段,这会很有用。

示例

<Form as |form transientData|>
  <form.Field @name="amount" @title="Amount" @type="input-number" as |field|>
    <field.Control />
  </form.Field>

  {{#if (gt transientData.amount 200)}}
    <form.Field @name="confirmed" @title="Confirm" @type="checkbox" as |field|>
      <field.Control>I know what I'm doing</field.Control>
    </form.Field>
  {{/if}}
</Form>

参数

@data

表单数据的初始状态。

FormKit 要求传入纯 JavaScript 对象(POJO)。 在内部,它将该对象克隆为草稿状态、跟踪补丁,并且只修改自己的内部副本。

与字段 @name 匹配的键会自动预填充,包括嵌套对象和集合路径。

:information_source: @data 被视为不可变对象。编辑不会修改你传入的原始对象。如果在编辑期间需要保持某些外部状态同步,请在 @onSet 中显式处理。

:warning: 一个新的 @data 对象会重建整个表单,丢弃焦点和未保存的编辑。在表单打开期间保持其引用稳定。

从模型派生表单对象时,在类字段或构造函数中只构建一次:

formData = getProperties(this.args.model, "foo", "bar", "baz");

避免使用在表单打开期间会重新计算的 getter 或 (hash ...),例如在 @onSet 或 @onSubmit 中把数据写回模型之后。如果模型本身可能发生变化,请针对每个模型重新创建所属组件,例如 {{#each (array @model) as |model|}}。

参数

  • data (对象):传递给模板的数据对象。

示例

<Form @data={{hash foo="bar"}} as |form|>
  <form.Field @name="foo" @title="Foo" @type="input" as |field|>
    <!-- This input will have "bar" as its initial value -->
    <field.Control />
  </form.Field>
</Form>

@onRegisterApi

表单实例创建时调用的回调,开发者可以通过它与表单进行 JavaScript 层面的交互。

参数

  • callback (对象):包含回调函数的对象。
  • callback.get (函数):返回给定字段名称的当前值。
  • callback.submit (函数):用于提交表单的函数。
  • callback.reset (函数):用于重置表单的函数。
  • callback.set (函数):用于在表单数据对象上设置键/值的函数。
  • callback.setProperties (函数):用于在表单数据对象上设置对象的函数。
  • callback.addError (函数):用于以编程方式添加错误的函数。
  • callback.removeError (函数):用于移除单个字段错误的函数。
  • callback.removeErrors (函数):用于清除所有错误的函数。
  • callback.isDirty (布尔值):已跟踪属性,暴露表单的脏状态(dirty state)。做出更改后它会变为 true,重置后又恢复为 false。

示例

registerAPI({ get, submit, reset, set, addError }) {
  // Interact with the form API
  get("foo");
  submit();
  reset();
  set("foo", 1);
  addError("foo", { title: "Foo", message: "Something went wrong" });
}
<Form @onRegisterApi={{this.registerAPI}} />

@onSubmit

在表单提交且有效时调用的回调函数。

参数

  • data(对象):表单当前的草稿数据。

示例

handleSubmit({ username, age }) {
  console.log(username, age);
}
<Form @onSubmit={{this.handleSubmit}} as |form|>
  <form.Field @name="username" @title="Username" @type="input" as |field|>
    <field.Control />
  </form.Field>
  <form.Field @name="age" @title="Age" @type="input-number" as |field|>
    <field.Control />
  </form.Field>
  <form.Submit />
</Form>

@onReset

在 FormKit 将草稿数据回滚到初始状态并清除错误后调用的回调函数。

参数

  • data(对象):回滚后的草稿数据。

示例

handleReset(data) {
  console.log("reset to", data);
}
<Form @data={{this.formData}} @onReset={{this.handleReset}} as |form|>
  <form.Field @name="username" @title="Username" @type="input" as |field|>
    <field.Control />
  </form.Field>

  <form.Reset />
</Form>

@validate

直接添加到表单的自定义验证回调函数。它在每次验证过程中运行一次,在字段级验证之后执行。

示例

@action
myValidation(data, { addError }) {
  if (data.foo !== data.bar) {
    addError("foo", { title: "Foo", message: "Bar must be equal to Foo" });
  }
}
<Form @validate={{this.myValidation}} />

异步示例:

@action
async myValidation(data, { addError }) {
  try {
    await ajax("/check-username", {
      type: "POST",
      data: { username: data.username }
    });
  } catch(e) {
    addError("username", { title: "Username", message: "Already taken!" });
  }
}

@validateOn

控制 FormKit 何时进行验证。

  • 接受的值:submit(默认)、change、focusout 和 input。

示例

<Form @validateOn="change" />

@onDirtyCheck

在路由转换期间且表单内容已更改时使用的回调函数。返回真值以显示内置的"表单内容已更改"确认对话框,返回假值则跳过。

参数

  • transition(Transition):正在处理的 Ember 路由转换。

示例

@action
onDirtyCheck(transition) {
  return transition.to?.name !== "wizard.step";
}
<Form @onDirtyCheck={{this.onDirtyCheck}} />

字段

@name

字段必须具有唯一的名称。此名称用于读写表单数据对象上的值,也用于验证。

名称不能包含 . 或 -。点号保留用于嵌套路径,例如 profile.location.city。

示例

<form.Field @name="foo" @title="Foo" @type="input" as |field|>
  <field.Control />
</form.Field>

@title

字段必须具有标题。标题将显示在控件上方,也用于验证。

示例

<form.Field @name="foo" @title="Foo" @type="input" as |field|>
  <field.Control />
</form.Field>

@type

字段必须具有类型。类型决定渲染哪个控件组件。可用类型包括:

  • 输入类型:input(默认为 text)、input-text、input-number、input-email、input-password、input-url、input-tel、input-date、input-time、input-datetime-local、input-color、input-month、input-week、input-range、input-search、input-hidden
  • 其他控件:checkbox、code、calendar、color、composer、custom、emoji、icon、image、menu、password、question、radio-group、select、tag-chooser、textarea、toggle

示例

<form.Field @name="foo" @title="Foo" @type="input" as |field|>
  <field.Control />
</form.Field>

@description

描述是可选的,设置后将显示在标题下方。

示例

<form.Field
  @name="foo"
  @title="Foo"
  @description="Bar"
  @type="input"
  as |field|
>
  <field.Control />
</form.Field>

@helpText

帮助文本是可选的,设置后将显示在字段下方。

示例

<form.Field @name="foo" @title="Foo" @helpText="Baz" @type="input" as |field|>
  <field.Control />
</form.Field>

@showTitle

默认情况下,标题将显示在控件顶部。通过将此属性设置为 false,可以选择不渲染标题。

示例

<form.Field
  @name="foo"
  @title="Foo"
  @showTitle={{false}}
  @type="input"
  as |field|
>
  <field.Control />
</form.Field>

@disabled

可以禁用字段以防止对其进行任何更改。

示例

<form.Field
  @name="foo"
  @title="Foo"
  @disabled={{true}}
  @type="input"
  as |field|
>
  <field.Control />
</form.Field>

@tooltip

允许在字段标题旁边显示工具提示。未显示标题时不会显示。可以传入字符串或 <DTooltip /> 组件。

示例

<Form as |form|>
  <form.Field
    @name="foo"
    @title="Foo"
    @type="input"
    @tooltip="a nice input"
    as |field|
  >
    <field.Control />
  </form.Field>
</Form>
<Form as |form|>
  <form.Field
    @name="foo"
    @title="Foo"
    @type="input"
    @tooltip={{component DTooltip content="a nice input"}}
    as |field|
  >
    <field.Control />
  </form.Field>
</Form>

@validation

请阅读专门的验证章节。

@validate

请阅读专门的自定义验证章节。

@onSet

默认情况下,当更改字段的值时,该值会被设置到表单的内部数据对象上。不过,你可以选择对某个字段的这一过程进行完全控制。

示例

@action
handleFooChange(value, { set, name, parentName, index }) {
  set("foo", value + "-bar");
}
<form.Field
  @name="foo"
  @title="Foo"
  @type="input"
  @onSet={{this.handleFooChange}}
  as |field|
>
  <field.Control />
</form.Field>

:information_source: 如果你需要在特定情况下获得更多响应性,可以使用 @onSet 来同时修改初始数据对象。

传递给 @onSet 的第二个参数包含:

  • set(name, value):更新表单草稿状态
  • name:字段的完整名称
  • parentName:嵌套字段的父路径
  • index:位于集合中时的当前集合索引

示例

@action
handleFooChange(value, { set }) {
  set("foo", value + "-bar");
  this.model.foo = value + "-bar";
}
<Form @data={{this.model}} as |form|>
  <form.Field
    @name="foo"
    @title="Foo"
    @type="input"
    @onSet={{this.handleFooChange}}
    as |field|
  >
    <field.Control />
  </form.Field>
</Form>

产出的参数

该字段会产出一个字段对象。由 @type 确定的控件组件可通过 field.Control 使用。

<form.Field @name="foo" @title="Foo" @type="input" as |field|>
  <field.Control />
</form.Field>

field.Control

field.Control 是由 @type 确定的控件组件。你可以直接向它传递控件特定的属性(例如 @height、@lang、placeholder)。

:information_source: field.Control 是受支持的 API。较早的产出名称(例如 field.Input)已弃用。

field

产出的 field 对象提供对字段数据和辅助方法的访问:

名称 描述
Control 由 @type 设置的控件的上下文组件
id 用于控件的无障碍 ID
errorId 字段错误容器的 ID
name 完整字段名称,包括嵌套路径前缀
value 来自草稿数据的当前值
set 用于设置字段值的函数

控件

我们在这里所说的控件,指的是允许用户输入数据的 UI 小部件。最基本的形式是一个输入框。控件类型通过字段上的 @type 来指定。

:information_source: 你可以向底层控件传递 HTML 属性。

示例

<Form as |form|>
  <form.Field
    @name="query"
    @title="Query"
    @type="input"
    @description="You should make sure the query doesn't include bots."
    as |field|
  >
    <field.Control placeholder="Foo" />
  </form.Field>
</Form>

@format

控件接受 @format 属性,其取值可以是 small、medium、large 或 full。

Form Kit 为每个控件设置了默认值,但你可以使用 @format 来覆盖它们:

  • small:100px
  • medium:220px
  • large:400px
  • full:100%

此外,还提供了以下 CSS 变量用于自定义这些默认值:

  • small:--form-kit-small-input
  • medium:--form-kit-medium-input
  • large:--form-kit-large-input

@labelFormat

独立于 @format 覆盖标题和描述(标签区域)的宽度。当较长的描述需要比输入框本身更多的空间时很有用,例如 @format="small" 配合 @labelFormat="full" 可以保持小输入框,同时让描述跨越整个表单。仅在标签区域需要与字段不同时才输出该属性;否则两者都继承自 @format。可用取值请查看 @format。

复选框

渲染一个 <input type="checkbox"> 元素。

:information_source: 何时使用单个复选框 只有 2 个选项:是/否。感觉像是同意某件事。勾选复选框不会保存;下方还有提交按钮。

示例

<Form as |form|>
  <form.Field @name="approved" @title="Approved" @type="checkbox" as |field|>
    <field.Control />
  </form.Field>
</Form>

日历

渲染一个日期选择器和一个时间输入框。在移动设备上,日期选择器会被日期输入框替换。

@includeTime

是否显示时间输入框。默认为 true。

示例

<Form as |form|>
  <form.Field @name="start" @title="Start" @type="calendar" as |field|>
    <field.Control @includeTime={{false}} />
  </form.Field>
</Form>

@expandedDatePickerOnDesktop

在桌面上以展开形式显示日期选择器。默认为 true。

示例

<Form as |form|>
  <form.Field @name="start" @title="Start" @type="calendar" as |field|>
    <field.Control @expandedDatePickerOnDesktop={{false}} />
  </form.Field>
</Form>

Code

渲染一个 <CodeEditor /> 组件。

Tab 缩进,Shift-Tab 减少缩进。要将键盘焦点移出编辑器,请先按 Escape 再按 Tab(或 Shift-Tab)。如果补全面板或搜索面板处于打开状态,请先用 Escape 将其关闭。

@height

以像素为单位设置编辑器的高度。

@lang

设置语言快捷方式:css、html、javascript、json、scss、sql、text、yaml 中的一个,或通过 api.registerCodeEditorLanguage 注册的名称。

示例

<Form as |form|>
  <form.Field @name="query" @title="Query" @type="code" as |field|>
    <field.Control @lang="sql" @height={{400}} />
  </form.Field>
</Form>

Color

渲染一个带有可选预设色板的颜色输入框。

通用控件参数:

  • @colors:预设颜色的数组
  • @usedColors:已使用颜色的数组
  • @collapseSwatches:将色板收起为菜单
  • @collapseSwatchesLabel:收起色板按钮的标签
  • @allowNamedColors:允许使用命名颜色,而不只是十六进制值
  • @fallbackValue:留空时失焦后恢复的值

示例

<Form as |form|>
  <form.Field @name="color" @title="Color" @type="color" as |field|>
    <field.Control
      @colors={{array "0088CC" "FFCC00"}}
      @usedColors={{array "FFCC00"}}
    />
  </form.Field>
</Form>

Composer

渲染一个 <DEditor /> 组件。

@height

设置撰写器的高度。

示例

<Form as |form|>
  <form.Field @name="message" @title="Message" @type="composer" as |field|>
    <field.Control @height={{400}} />
  </form.Field>
</Form>

@preview

控制撰写器预览的显示。默认为 false。

示例

<Form as |form|>
  <form.Field @name="message" @title="Message" @type="composer" as |field|>
    <field.Control @preview={{true}} />
  </form.Field>
</Form>

Custom

渲染一个用于自定义内容的包装器。当你想提供自己的控件标记但仍使用 FormKit 字段元数据和状态时,这是正确的选择。

示例

<Form as |form|>
  <form.Field @name="slug" @title="Slug" @type="custom" as |field|>
    <field.Control>
      <MyCustomControl
        id={{field.id}}
        @value={{field.value}}
        @onChange={{field.set}}
      />
    </field.Control>
  </form.Field>
</Form>

Emoji

渲染一个 <EmojiPicker /> 组件。

@context

将选择器上下文传递给 <EmojiPicker />。

示例

<Form as |form|>
  <form.Field @name="emoji" @title="Emoji" @type="emoji" as |field|>
    <field.Control @context="chat" />
  </form.Field>
</Form>

Icon

渲染一个 <DIconGridPicker /> 组件。 示例

<Form as |form|>
  <form.Field @name="icon" @title="Icon" @type="icon" as |field|>
    <field.Control />
  </form.Field>
</Form>

Image

渲染一个 <UppyImageUploader /> 组件。

通用控制参数:

  • @type:传递给 <UppyImageUploader /> 的上传器上下文
  • @placeholderUrl:可选的占位图片

上传处理

默认情况下,该组件会设置一个上传对象。通常只需要上传的 URL 和 ID。为此,可以使用字段上的 @onSet 属性:

@action
handleUpload(upload, { set }) {
  set("upload_id", upload.id);
  set("upload_url", getURL(upload.url));
}
<Form as |form|>
  <form.Field
    @name="upload"
    @title="Upload"
    @type="image"
    @onSet={{this.handleUpload}}
    as |field|
  >
    <field.Control />
  </form.Field>
</Form>

示例

<Form as |form|>
  <form.Field @name="upload" @title="Upload" @type="image" as |field|>
    <field.Control />
  </form.Field>
</Form>

Input

渲染一个 <input> 元素。

@type

输入变体作为字段 @type 的一部分,使用 input- 前缀指定。例如 @type="input"、@type="input-number" 或 @type="input-email"。@type="input" 默认为 text。

已允许的类型

  • input(默认为 text)
  • input-color
  • input-date
  • input-datetime-local
  • input-email
  • input-hidden
  • input-month
  • input-number
  • input-password
  • input-range
  • input-search
  • input-tel
  • input-text
  • input-time
  • input-url
  • input-week

特殊情况

  • checkbox 和 radio 有专用的控件
  • 文件上传应使用 @type="image"

示例

<Form as |form|>
  <form.Field @name="email" @title="Email" @type="input" as |field|>
    <field.Control />
  </form.Field>

  <form.Field @name="age" @title="Age" @type="input-number" as |field|>
    <field.Control />
  </form.Field>
</Form>

@before

在输入框之前渲染文本

示例

<Form as |form|>
  <form.Field @name="email" @title="Email" @type="input" as |field|>
    <field.Control @before="mailto:" />
  </form.Field>
</Form>

@after

在输入框之后渲染文本

示例

<Form as |form|>
  <form.Field @name="email" @title="Email" @type="input" as |field|>
    <field.Control @after=".com" />
  </form.Field>
</Form>

Menu

渲染一个带 yielded 菜单内容的 <DMenu /> 触发条件。

@preservePlacement

将 @preservePlacement={{true}} 传递给 <field.Control>,可以在菜单关闭前保持其初始解析的位置。这可以防止筛选结果导致已打开的菜单在其触发条件的上方与下方之间翻转。滚动和调整视口大小仍会更新其位置。每次打开都会重新选择其位置。默认为 false。

如果菜单内容增大,或所选一侧的可用空间减小,菜单不会切换到另一侧。已启用的偏移和视口高度限制仍然适用;对于可能增大的结果,请使用有约束、可滚动的内容区域。

@selection

要显示在触发条件上的文本。

产出的参数

Item

渲染一个可选择的行。接受 @value、@icon 和 @action 属性。

  • @value:允许为行分配一个值。
  • @icon:在行的开头显示一个图标。
  • @action:覆盖默认操作,默认操作会用该行的值设置字段的值。

内容将被产出。

Divider

渲染一个分隔符。

Container

渲染一个 div,其内容为产出的内容。

示例

<Form as |form|>
  <form.Field @name="email" @title="Email" @type="menu" as |field|>
    <field.Control as |menu|>
      <menu.Item @value={{1}} @icon="pencil-alt">Edit</menu.Item>
      <menu.Divider />
      <menu.Container class="foo">
        Bar
      </menu.Container>
      <menu.Item @action={{this.doSomething}}>Something</menu.Item>
    </field.Control>
  </form.Field>
</Form>

Password

渲染一个带可见性切换的密码输入框。

:information_source: 这与 @type="input-password" 不同。专用的 password 控件添加了显示/隐藏按钮。

示例

<Form as |form|>
  <form.Field @name="secret" @title="Secret" @type="password" as |field|>
    <field.Control />
  </form.Field>
</Form>

Question

渲染两个类型为 radio 的输入框,第一个是肯定回答,第二个是否定回答。

@yesLabel

允许自定义肯定回答的标签。

@noLabel

允许自定义否定回答的标签。

示例

<Form as |form|>
  <form.Field @name="email" @title="Email" @type="question" as |field|>
    <field.Control @yesLabel="Correct" @noLabel="Wrong" />
  </form.Field>
</Form>

RadioGroup

渲染共享一个通用名称的单选按钮列表。

示例

<Form as |form|>
  <form.Field @name="foo" @title="Foo" @type="radio-group" as |field|>
    <field.Control as |radioGroup|>
      <radioGroup.Radio @value="one">One</radioGroup.Radio>
      <radioGroup.Radio @value="two">Two</radioGroup.Radio>
      <radioGroup.Radio @value="three">Three</radioGroup.Radio>
    </field.Control>
  </form.Field>
</Form>

Radio 产出的参数

Title

允许渲染一个标题。

示例

<Form as |form|>
  <form.Field @name="foo" @title="Foo" @type="radio-group" as |field|>
    <field.Control as |RadioGroup|>
      <RadioGroup.Radio @value="one" as |radio|>
        <radio.Title>One title</radio.Title>
      </RadioGroup.Radio>
    </field.Control>
  </form.Field>
</Form>

Description

允许渲染一段描述。

示例

<Form as |form|>
  <form.Field @name="foo" @title="Foo" @type="radio-group" as |field|>
    <field.Control as |RadioGroup|>
      <RadioGroup.Radio @value="one" as |radio|>
        <radio.Description>One description</radio.Description>
      </RadioGroup.Radio>
    </field.Control>
  </form.Field>
</Form>

Select

渲染一个 <DNativeSelect /> 组件。

@includeNone

默认情况下,当字段为空或字段未标记 required 时,Select 会包含一个“无”选项。使用 @includeNone 覆盖此行为。

示例

<Form as |form|>
  <form.Field @name="fruits" @title="Fruits" @type="select" as |field|>
    <field.Control as |select|>
      <select.Option @value="1">Mango</select.Option>
      <select.Option @value="2">Apple</select.Option>
      <select.Option @value="3">Coconut</select.Option>
    </field.Control>
  </form.Field>
</Form>

Tag Chooser

渲染一个 <TagChooser /> 组件。

通用控件参数:

  • @allowCreate
  • @categoryId
  • @showAllTags
  • @excludeSynonyms
  • @excludeTagsWithSynonyms
  • @unlimited
  • @placeholder

示例

<Form as |form|>
  <form.Field @name="tags" @title="Tags" @type="tag-chooser" as |field|>
    <field.Control @categoryId={{1}} @allowCreate={{true}} />
  </form.Field>
</Form>

Textarea

渲染一个 <textarea> 元素。

@height

设置文本区域的高度。

示例

<Form as |form|>
  <form.Field
    @name="description"
    @title="Description"
    @type="textarea"
    as |field|
  >
    <field.Control @height={{120}} />
  </form.Field>
</Form>

@autoResize

让文本区域随内容增长(通过 <ExpandingTextArea> 渲染)。可以通过任意祖先上的 --expanding-text-area-min-height(默认 auto)和 --expanding-text-area-max-height(默认 none)自定义属性设置边界。

示例

<form.Field @name="description" @type="textarea" as |field|>
  <field.Control @autoResize={{true}} />
</form.Field>
[data-name="description"] {
  --expanding-text-area-min-height: 10rem;
  --expanding-text-area-max-height: 50rem;
}

Toggle

渲染一个 <DToggleSwitch /> 组件。

:information_source: 只有 2 种状态:已启用/已禁用。它应该给人开启某样东西的感觉。切换会立即生效,没有提交按钮。

示例

<Form as |form|>
  <form.Field @name="allowed" @title="Allowed" @type="toggle" as |field|>
    <field.Control />
  </form.Field>
</Form>

Layout

Form Kit 旨在提供良好的默认值,让你可以主要使用字段和控件。但是,如果你需要更多控制,我们提供了几个辅助工具:Row 和 Col、Section、Fieldset、Container 以及 Actions。

你还可以使用 Submit、Reset、Alert、CheckboxGroup、InputGroup 和 ConditionalContent 等实用工具。

Actions

Actions 是一个自定义的 Container,设计用于在表单页脚中包裹你的按钮。

示例

<Form as |form|>
  <form.Actions>
    <form.Submit />
  </form.Actions>
</Form>

Alert

在表单中显示一个警告。

@icon

警告提示中使用的可选图标。

示例

<form.Alert @icon="info-circle">
  Foo
</form.Alert>

@type

指定警告提示的类型。允许的类型:success、error、warning 或 info。

示例

<form.Alert @type="warning">
  Foo
</form.Alert>

Checkbox Group

CheckboxGroup 允许将复选框组合在一起。

示例

<form.CheckboxGroup @title="Preferences" as |group|>
  <group.Field @name="editable" @title="Editable" @type="checkbox" as |field|>
    <field.Control />
  </group.Field>
  <group.Field
    @name="searchable"
    @title="Searchable"
    @type="checkbox"
    as |field|
  >
    <field.Control />
  </group.Field>
</form.CheckboxGroup>

ConditionalContent

ConditionalContent 帮助你使用一个小的单选控件在互斥的内容块之间切换。

示例

<Form as |form|>
  <form.ConditionalContent @activeName="basic" as |conditional|>
    <conditional.Conditions as |Condition|>
      <Condition @name="basic">Basic</Condition>
      <Condition @name="advanced">Advanced</Condition>
    </conditional.Conditions>

    <conditional.Contents as |Content|>
      <Content @name="basic">
        <form.Alert>Basic settings</form.Alert>
      </Content>

      <Content @name="advanced">
        <form.Alert @type="warning">Advanced settings</form.Alert>
      </Content>
    </conditional.Contents>
  </form.ConditionalContent>
</Form>

Container

Container 允许你渲染一个类似于字段的块,而不将其绑定到特定数据。它对自定义控件很有用。

通用参数:

  • @title
  • @subtitle
  • @format
  • @direction

示例

<Form as |form|>
  <form.Container @title="Important" @subtitle="This is important">
    <!-- Container content here -->
  </form.Container>
</Form>

Fieldset

将内容包裹在 fieldset 中。

示例

<form.Fieldset @name="a-fieldset" class="my-fieldset">
  Foo
</form.Fieldset>

@title

显示 fieldset 的标题,将使用 legend 元素。

示例

<form.Fieldset @title="A title">
  Foo
</form.Fieldset>

@description

显示 fieldset 的描述。

示例

<form.Fieldset @description="A description">
  Foo
</form.Fieldset>

@name

设置 fieldset 的名称。如果你想使用 fieldset 测试辅助工具,这是必要的。

示例

<form.Fieldset @name="a-name">
  Foo
</form.Fieldset>

Input Group

输入组允许你将多个输入组合在同一行上。

示例

<Form as |form|>
  <form.InputGroup as |inputGroup|>
    <inputGroup.Field @title="Foo" @name="foo" @type="input" as |field|>
      <field.Control />
    </inputGroup.Field>
    <inputGroup.Field @title="Bar" @name="bar" @type="input" as |field|>
      <field.Control />
    </inputGroup.Field>
  </form.InputGroup>
</Form>

Reset

Reset 组件渲染一个 <DButton />,点击时将重置表单。它接受与标准 <DButton /> 相同的所有参数。标签和默认操作默认已设置。

示例

<form.Reset />

要进一步自定义 Reset 按钮,你可以根据需要传递额外的参数:

带额外参数的示例

<form.Reset @translatedLabel="Remove changes" />

Row and Col

Row 和 Col 让你能够在表单中使用简单的网格系统(12 列)。

示例

<Form as |form|>
  <form.Row as |row|>
    <row.Col @size={{4}}>
      <form.Field @name="foo" @title="Foo" @type="input" as |field|>
        <field.Control />
      </form.Field>
    </row.Col>
    <row.Col @size={{8}}>
      <form.Field @name="bar" @title="Bar" @type="input" as |field|>
        <field.Control />
      </form.Field>
    </row.Col>
  </form.Row>
</Form>

Section

Section 提供了一种创建带或不带标题的版块的简单方法。

@subtitle

在版块标题中显示次要文本。

示例

<Form as |form|>
  <form.Section @title="Settings">
    <!-- Section content here -->
  </form.Section>
</Form>

Submit

Submit 组件渲染一个 <DButton />,点击时将提交表单。它接受与标准 <DButton /> 相同的所有参数。标签、默认操作和主要样式默认已设置。

示例

<form.Submit />

要进一步自定义 Submit 按钮,你可以根据需要传递额外的参数:

带额外参数的示例

<form.Submit @translatedLabel="Send" />

Object

对象组件让你能够在表单中处理嵌套对象。

示例

<Form @data={{hash foo=(hash bar=1 baz=2)}} as |form|>
  <form.Object @name="foo" as |object data|>
    <object.Field @name="bar" @title="Bar" @type="input" as |field|>
      <field.Control />
    </object.Field>
    <object.Field @name="baz" @title="Baz" @type="input" as |field|>
      <field.Control />
    </object.Field>
  </form.Object>
</Form>

@name

对象必须有一个唯一的名称。该名称用作底层字段的前缀。

与字段名称一样,对象名称不应包含 . 或 -。

示例

<form.Object @name="foo" />

Nesting

对象可以接受嵌套的 Object 或 Collection。

示例

<Form @data={{hash foo=(hash bar=(hash baz=1 bol=2))}} as |form|>
  <form.Object @name="foo" as |parentObject|>
    <parentObject.Object @name="bar" as |childObject data|>
      <childObject.Field @name="baz" @title="Baz" @type="input" as |field|>
        <field.Control />
      </childObject.Field>
    </parentObject.Object>
  </form.Object>
</Form>

<Form @data={{hash foo=(hash bar=(array 1 2))}} as |form|>
  <form.Object @name="foo" as |parentObject|>
    <parentObject.Collection @name="bar" as |collection index|>
      <collection.Field @title="Baz" @type="input" as |field|>
        <field.Control />
      </collection.Field>
      <form.Button
        class={{concat "remove-" index}}
        @action={{fn collection.remove index}}
      >Remove</form.Button>
    </parentObject.Collection>
  </form.Object>
</Form>

Collection

集合组件让你能够在表单中处理数组。

它产出三个值:集合 API、当前索引和当前项。

示例

<Form @data={{hash foo=(array (hash bar=1) (hash bar=2))}} as |form|>
  <form.Collection @name="foo" as |collection index item|>
    <collection.Field @name="bar" @title="Bar" @type="input" as |field|>
      <field.Control placeholder={{concat "item-" index}} />
    </collection.Field>
  </form.Collection>
</Form>

@name

集合必须有一个唯一的名称。该名称用作底层字段的前缀。

例如,如果集合的名称为 "foo",那么集合中名为 "bar" 的第二个字段实际的名称将是 "foo.1.bar"。

与字段名称一样,集合名称不应包含 . 或 -。

示例

<form.Collection @name="foo" />

@tagName

集合默认渲染为 <div class="form-kit__collection">。你可以使用 @tagName 改变这一行为。

示例

<form.Collection @name="foo" @tagName="tr" />

原始类型数组

如果你的数据形态是原始类型数组,例如:[1, 2, 3],form-kit 能够处理。在这种情况下,你只需省略字段上的 name,因为 name 会根据索引自动生成。

示例

<Form @data={{hash foo=(array 1 2)}} as |form|>
  <form.Collection @name="foo" as |collection|>
    <collection.Field @title="Baz" @type="input" as |field|>
      <field.Control />
    </collection.Field>
  </form.Collection>
</Form>

嵌套

集合可以接受嵌套的 Object 或 Collection。

示例

<Form
  @data={{hash foo=(array (hash bar=(hash baz=1)) (hash bar=(hash baz=2)))}}
  as |form|
>
  <form.Collection @name="foo" as |collection|>
    <collection.Object @name="bar" as |object|>
      <object.Field @name="baz" @title="Baz" @type="input" as |field|>
        <field.Control />
      </object.Field>
    </collection.Object>
  </form.Collection>
</Form>

<Form
  @data={{hash
    foo=(array (hash bar=(array (hash baz=1))) (hash bar=(array (hash baz=2))))
  }}
  as |form|
>
  <form.Collection @name="foo" as |parent parentIndex|>
    <parent.Collection @name="bar" as |child childIndex|>
      <child.Field @name="baz" @title="Baz" @type="input" as |field|>
        <field.Control />
      </child.Field>
    </parent.Collection>
  </form.Collection>
</Form>

向集合添加一项

<Form /> 组件产出的对象有一个 addItemToCollection 函数,你可以调用它向特定集合添加一项。

示例

<Form @data={{hash foo=(array (hash bar=1) (hash bar=2))}} as |form|>
  <form.Button @action={{fn form.addItemToCollection "foo" (hash bar=3)}}>
    Add
  </form.Button>

  <form.Collection @name="foo" as |collection index|>
    <collection.Field @name="bar" @title="Bar" @type="input" as |field|>
      <field.Control placeholder={{concat "item-" index}} />
    </collection.Field>
  </form.Collection>
</Form>

从集合中移除一项

<Collection /> 组件产出的对象有一个 remove 函数,你可以调用它从此集合中移除一项,它接受索引作为参数

示例

<Form @data={{hash foo=(array (hash bar=1) (hash bar=2))}} as |form|>
  <form.Collection @name="foo" as |collection index|>
    <collection.Field @name="bar" @title="Bar" @type="input" as |field|>
      <field.Control />
      <form.Button @action={{fn collection.remove index}}>
        Remove
      </form.Button>
    </collection.Field>
  </form.Collection>
</Form>

验证

字段接受一个 @validation 属性,用于描述该字段的验证规则。

可用规则列表

Accepted

该值必须是 "yes"、"on"、true、1 或 "true"。适用于复选框输入,通常用于需要验证某人是否已接受条款的场景。

示例

<form.Field
  @name="terms"
  @title="Terms"
  @type="checkbox"
  @validation="accepted"
  as |field|
>
  <field.Control />
</form.Field>

Between

检查数值是否介于最小值和最大值之间。

示例

<form.Field
  @name="amount"
  @title="Amount"
  @type="input-number"
  @validation="between:1,10"
  as |field|
>
  <field.Control />
</form.Field>

dateAfterOrEqual

检查日历值是否晚于或等于指定日期。格式必须为 YYYY-MM-DD。

示例

<form.Field
  @name="start"
  @title="Start"
  @type="calendar"
  @validation="dateAfterOrEqual:2022-02-01"
  as |field|
>
  <field.Control />
</form.Field>

dateBeforeOrEqual

检查日历值是否早于或等于指定日期。格式必须为 YYYY-MM-DD。

示例

<form.Field
  @name="start"
  @title="Start"
  @type="calendar"
  @validation="dateBeforeOrEqual:2022-02-01"
  as |field|
>
  <field.Control />
</form.Field>

EndsWith

检查字符串是否以给定后缀结束。

示例

<form.Field
  @name="domain"
  @title="Domain"
  @type="input"
  @validation="endsWith:.com"
  as |field|
>
  <field.Control />
</form.Field>

Integer

检查值是否为整数。

示例

<form.Field
  @name="age"
  @title="Age"
  @type="input-number"
  @validation="integer"
  as |field|
>
  <field.Control />
</form.Field>

Length

检查输入的值是否超过给定长度,或介于两个长度值之间。

示例

<form.Field
  @name="username"
  @title="Username"
  @type="input"
  @validation="length:5,16"
  as |field|
>
  <field.Control />
</form.Field>

Number

检查输入是否为 isNaN() 判定的有效数字。

:information_source: 在适用的情况下,优先使用数字输入:@type="input-number"。

示例

<form.Field
  @name="amount"
  @title="Amount"
  @type="input"
  @validation="number"
  as |field|
>
  <field.Control />
</form.Field>

Required

检查输入是否为空。

required:trim 在检查值之前会去除首尾空白字符。

示例

<form.Field
  @name="username"
  @title="Username"
  @type="input"
  @validation="required:trim"
  as |field|
>
  <field.Control />
</form.Field>

StartsWith

检查字符串是否以给定前缀开始。

示例

<form.Field
  @name="handle"
  @title="Handle"
  @type="input"
  @validation="startsWith:@"
  as |field|
>
  <field.Control />
</form.Field>

URL

检查输入值看起来是否是包含协议、格式正确的 URL。这不会检查该 URL 是否实际可解析。

示例

<form.Field
  @name="endpoint"
  @title="Endpoint"
  @type="input-url"
  @validation="url"
  as |field|
>
  <field.Control />
</form.Field>

组合规则

规则可以使用管道运算符组合:|。

示例

<form.Field
  @name="username"
  @title="Username"
  @type="input"
  @validation="required|length:5,16"
  as |field|
>
  <field.Control />
</form.Field>

自定义验证

自定义验证器可以调用 preventSubmit 来停止当前提交,而不会将表单标记为无效。它只影响当前这次验证过程,必须在后续再次调用才能阻止之后的提交尝试。在非提交触发的验证过程中调用它没有任何效果。

Field

Field 接受一个 @validate 属性,允许你定义一个回调函数来验证单个字段。

参数

  • name (string):被验证的表单字段的名称。
  • value (unknown):当前字段值。
  • context (Object)
    • context.data (Object):当前表单草稿数据。
    • context.type (string):字段控件类型。
    • context.addError (Function):如果验证失败则添加一个错误。
    • context.preventSubmit (Function):在不添加错误的情况下阻止当前提交。

示例

@action
validateUsername(name, value, { data, addError }) {
  if (value === data.slug) {
    addError(name, {
      title: "Username",
      message: "Username and slug must differ.",
    });
  }
}
<form.Field
  @name="username"
  @title="Username"
  @type="input"
  @validate={{this.validateUsername}}
  as |field|
>
  <field.Control />
</form.Field>

Form

Form 接受一个 @validate 属性,允许你定义一个回调函数,在每次验证过程中对完整的表单状态验证一次。

参数

  • data (Object):包含用于验证的附加信息的数据对象。
  • handlers (Object):包含处理函数的对象。
    • handlers.addError (Function):如果验证失败则添加一个错误的函数。
    • handlers.removeError (Function):清除现有错误的函数。
    • handlers.preventSubmit (Function):在不添加错误的情况下阻止当前提交的函数。

示例

@action
validateForm(data, { addError, removeError }) {
  if (data.start && data.end && data.end < data.start) {
    addError("end", {
      title: "End",
      message: "End must be after start.",
    });
  } else {
    removeError("end");
  }
}
<Form @validate={{this.validateForm}} as |form|>
  <form.Field @name="start" @title="Start" @type="input-date" as |field|>
    <field.Control />
  </form.Field>

  <form.Field @name="end" @title="End" @type="input-date" as |field|>
    <field.Control />
  </form.Field>

  <form.Submit />
</Form>

:information_source: 未知的验证规则名称会在运行时抛出。扩展 FormKit 时,请保持上述规则列表与实现同步。

辅助方法

辅助方法由一些块产生,例如 Form,或者作为参数提供给回调函数。它们让你能够以简单清晰的方式与表单状态交互。

set

set 允许你为表单数据中的特定字段赋值。

参数

  • name (string):要设置值的字段的名称。
  • value (number):要设置的值。

示例

set("foo", 1);

使用由表单产生的 set 辅助方法:

<Form as |form|>
  <DButton @action={{fn form.set "foo" 1}} @translatedLabel="Set foo" />
</Form>

setProperties

setProperties 允许你将一个对象赋值给表单数据。

参数

  • data (object):一个 POJO,其中每个键都将通过其对应的值被设置到表单上。

示例

setProperties({ foo: 1, bar: 2 });

使用由表单产生的 setProperties 辅助方法:

<Form as |form|>
  <DButton
    @action={{fn form.setProperties (hash foo=1 bar=2)}}
    @translatedLabel="Set foo and bar"
  />
</Form>

addError

addError 允许你向表单中的特定字段添加错误消息。

参数

  • name (string):无效字段的名称。
  • error (object):错误的数据
    • title (string):错误的标题,通常是字段的翻译名称
    • message (string):错误消息

示例

addError("foo", { title: "Foo", message: "This should be another thing." });

自定义

插件出口

FormKit 可以与 <PluginOutlet /> 无缝协作。你可以在表单中使用插件出口来扩展其功能:

<Form as |form|>
  <PluginOutlet @name="above-foo-form" @outletArgs={{hash form=form}} />
</Form>

然后,在连接器中,你可以使用出口参数来添加自定义字段:

<template>
  <@outletArgs.form.Field @name="bar" @title="Bar" @type="input" as |field|>
    <field.Control />
  </@outletArgs.form.Field>
</template>

样式

所有 FormKit 组件都会传播属性,允许你设置类名和数据属性,例如:

<Form class="my-form" as |form|>
  <form.Field
    @name="foo"
    @title="Foo"
    @type="input"
    class="my-field"
    as |field|
  >
    <field.Control class="my-control" />
  </form.Field>
</Form>

自定义控件

借助 form 和 field 产生的属性,创建自定义控件非常简单:

<Form as |form|>
  <form.Field
    @name="foo"
    @title="Foo"
    @type="custom"
    class="my-field"
    as |field|
  >
    <field.Control>
      <MyCustomControl id={{field.id}} @onChange={{field.set}} />
    </field.Control>
  </form.Field>
</Form>

form 上的通用值

名称 描述
set 按名称设置任意字段,例如 set("bar", 1)
setProperties 一次设置多个字段值
addItemToCollection 通过路径向集合追加一项

field 上的通用值

名称 描述
id 输入 ID
errorId 错误容器 ID
name 完整的嵌套字段路径
value 草稿状态中当前字段的值
set 设置当前字段的值

Javascript 断言

表单

表单元素断言位于 assert.form(...).*。默认情况下,它会选择第一个 "form" 元素。

参数

  • target (string | HTMLElement):表单元素或选择器。

hasErrors()

断言表单错误摘要包含给定的字段错误。

参数

  • fields (Object):字段名称到错误消息的映射,例如 { username: "Required" }。
  • message (string) [可选]:测试的描述。

示例

assert.form().hasErrors({ username: "Required" }, "the form shows errors");

hasNoErrors()

断言表单错误摘要不存在。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().hasNoErrors("the form is valid");

字段

字段元素断言位于 assert.form(...).field(...).*。

参数

  • name (string):字段的名称。

示例

assert.form().field("foo");

hasValue()

断言字段的 value 与 expected 文本匹配。

参数

  • expected (anything):期望值。
  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").hasValue("bar", "user has set the value");

hasNoValue()

断言字段为空白。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").hasNoValue("the field starts blank");

isDisabled()

断言 field 已禁用。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").isDisabled("the field is disabled");

isEnabled()

断言 field 已启用。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").isEnabled("the field is enabled");

hasTitle()

断言字段标题与期望的文本匹配。

参数

  • expected (anything):期望值。
  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").hasTitle("Foo", "it shows the field title");

hasDescription()

断言字段描述与期望的文本匹配。

参数

  • expected (anything):期望值。
  • message (string) [可选]:测试的描述。

示例

assert
  .form()
  .field("foo")
  .hasDescription("Helpful copy", "it shows the description");

hasError()

断言 field 具有特定错误。

参数

  • error (string):字段上的错误消息。
  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").hasError("Required", "it is required");

hasNoErrors()

断言 field 没有错误。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").hasNoErrors("it is valid");

exists()

断言 field 存在。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").exists("it has the foo field");

doesNotExist()

断言 field 不存在。

参数

  • message (string) [可选]:测试的描述。

示例

assert.form().field("foo").doesNotExist("it has no foo field");

hasCharCounter()

断言 field 具有字符计数器。

参数

  • current (整数): 字段的当前长度。
  • max (整数): 字段的最大长度。
  • message (字符串) [可选]: 测试的描述。

示例

assert.form().field("foo").hasCharCounter(2, 5, "it has updated the counter");

Fieldset

字段元素的断言可在 assert.form(...).fieldset(...).* 获取。

参数

  • name (字符串): fieldset 的名称。

示例

assert.form().fieldset("foo");

hasTitle()

断言 fieldset 的 title 与 expected 值匹配。

参数

  • expected (任意): 期望值。
  • message (字符串) [可选]: 测试的描述。

示例

assert.form().fieldset("foo").hasTitle("bar", "it has the correct title");

hasDescription()

断言 fieldset 的 description 与 expected 值匹配。

参数

  • expected (任意): 期望值。
  • message (字符串) [可选]: 测试的描述。

示例

assert
  .form()
  .fieldset("foo")
  .hasDescription("bar", "it has the correct description");

includesText()

断言 fieldset 已产出 expected 值。

参数

  • expected (任意): 期望值。
  • message (字符串) [可选]: 测试的描述。

示例

assert.form().fieldset("foo").includesText("bar", "it has the correct text");

exists()

断言 fieldset 存在。

参数

  • message (字符串) [可选]: 测试的描述。

示例

assert.form().fieldset("foo").exists("the fieldset is rendered");

doesNotExist()

断言 fieldset 不存在。

参数

  • message (字符串) [可选]: 测试的描述。

示例

assert.form().fieldset("foo").doesNotExist("the fieldset is hidden");

Javascript 助手

表单

FormKit 助手允许你通过清晰且富有表现力的 API 来操作表单及其字段。

示例

import formKit from "discourse/tests/helpers/form-kit-helper";

test("fill in input", async function (assert) {
  await render(
    <template>
      <Form class="my-form" as |form data|>
        <form.Field @name="foo" @title="Foo" @type="input" as |field|>
          <field.Control />
        </form.Field>
      </Form>
    </template>
  );

  const myForm = formKit(".my-form");
});

submit()

提交关联的表单。

示例

formKit().submit();

reset()

重置关联的表单。

示例

formKit().reset();

field()

返回指定名称字段的字段助手。

参数

  • name (字符串): 字段的名称。

示例

const field = formKit().field("foo");

hasField()

检查表单中是否存在具有给定名称的字段。

参数

  • name (字符串): 字段的名称。

示例

formKit().hasField("foo");

字段

参数

  • name (字符串): 字段的名称。

value()

返回受支持控件的当前 UI 值。

示例

formKit().field("foo").value();

options()

返回 @type="select" 字段的可用选项值。

示例

formKit().field("foo").options();

fillIn()

可用于 @type="input"、@type="input-text"、@type="input-number"、@type="password"、@type="color"、@type="code"、@type="textarea" 和 @type="composer" 等类输入控件。

参数

  • value (字符串 | 整数 | undefined): 要在输入上设置的值。

示例

await formKit().field("foo").fillIn("bar");

toggle()

可用于 @type="checkbox"、@type="toggle" 或 @type="password" 字段。

将切换控件的状态。对于密码控件而言,它实际上会切换字段的可见性。

示例

await formKit().field("foo").toggle();

accept()

可用于 @type="question" 字段。

示例

await formKit().field("foo").accept();

refuse()

可用于 @type="question" 字段。

示例

await formKit().field("foo").refuse();

select()

可用于 @type="select"、@type="menu"、@type="icon"、@type="radio-group" 和 @type="color" 字段。

将选择给定值。

参数

  • value (字符串 | 整数 | undefined): 要选择的值。

示例

await formKit().field("foo").select("bar");

setDay()

可用于 @type="calendar" 字段。

参数

  • day(整数):要选择的月份中的日期。

示例

await formKit().field("start").setDay(15);

setTime()

可用于 @type="calendar" 字段。

参数

  • time(字符串):要设置的时间,例如 "14:30"。

示例

await formKit().field("start").setTime("14:30");

isDisabled()

返回字段是否已禁用。

示例

formKit().field("foo").isDisabled();

hasPrefix()

可用于 @type="color" 字段。返回颜色输入框是否渲染其前缀。

示例

formKit().field("color").hasPrefix();

swatches()

可用于 @type="color" 字段。以 { color, isUsed, isDisabled } 的形式返回已渲染的色板。

示例

formKit().field("color").swatches();

triggerEvent()

在字段的输入元素上触发 DOM 事件。

参数

  • eventName(字符串):要触发的事件。
  • options(对象)[可选]:额外的事件选项。

示例

await formKit().field("foo").triggerEvent("blur");

系统规格页面对象

表单

FormKit 页面对象组件可用于帮助您为表单编写系统规格。

参数

  • target(字符串):表单的选择器。

示例

form = PageObjects::Components::FormKit.new(".my-form")

submit

提交表单。

示例

form.submit

reset

重置表单。

示例

form.reset

has_an_alert?

检查表单是否渲染了带有给定消息的提示框。

示例

form.has_an_alert?("message")
expect(form).to have_an_alert("message")

has_field_with_name?

检查是否存在具有给定 data-name 的字段。

示例

form.has_field_with_name?("foo")

has_no_field_with_name?

检查具有给定 data-name 的字段是否不存在。

示例

form.has_no_field_with_name?("foo")

container

返回指定名称容器的容器辅助方法。

示例

container = form.container("advanced-settings")
container.has_content?("More options")

choose_conditional

通过单选按钮的值选择 ConditionalContent 分支。

示例

form.choose_conditional("advanced")

字段

field 辅助方法允许您与表单中的特定字段进行交互。

参数

  • name(字符串):字段的名称。

示例

field = form.field("foo")

value

返回字段的值。

示例

field.value
expect(field).to have_value("bar")

has_value?

检查字段值是否与期望值匹配。

示例

field.has_value?("bar")

checked?

返回复选框的控件是否已勾选。

示例

field.checked?
expect(field).to be_checked

unchecked?

返回复选框的控件是否未勾选。

示例

field.unchecked?
expect(field).to be_unchecked

disabled?

返回字段是否已禁用。

示例

field.disabled?
expect(field).to be_disabled

enabled?

返回字段是否已启用。

示例

field.enabled?
expect(field).to be_enabled

toggle

允许切换字段。可用于 @type="checkbox"、@type="password" 和 @type="toggle"。

示例

field.toggle

fill_in

允许用给定的值填充字段。可用于 @type="input"、@type="input-*" 变体、@type="password"、@type="color"、@type="textarea"、@type="code" 和 @type="composer"。

示例

field.fill_in("bar")

select

允许在字段中选择指定的值。可用于 @type="select"、@type="icon"、@type="menu"、@type="radio-group"、@type="question"、标签选择器,以及自定义多选控件。

示例

field.select("bar")

accept

允许接受字段。仅可用于:@type="question"。

示例

field.accept

refuse

允许拒绝字段。仅可用于:@type="question"。

示例

field.refuse

upload_image

接收文件系统上的图片路径,并为该字段上传图片。仅对 @type="image" 控制可用。

示例

field.upload_image(image_file_path)

has_errors?

检查该字段是否渲染了已送出的错误消息。

示例

field.has_errors?("Required")

has_no_errors?

检查该字段没有错误。

示例

field.has_no_errors?

has_selected_names?

检查 @type="tag-chooser" 字段的所选名称。

示例

field.has_selected_names?("support", "meta")