October cms-Backend (后端-表单)

表单

介绍

Form behavior是控制器修改器,用于轻松地将表单功能添加到后端页面。
该行为提供了三个页面,分别称为“创建”,“更》〉新”和“预览”。
“预览”页面是“更新”页面的只读版本。
当您使用表单行为时,无需在控制器中定义create, update 和 preview action-behavior将为您完成。
但是,您应该提供相应的视图文件。
表单行为取决于表单字段定义和模型类。
为了使用表单行为,您应该将其添加到控制器类的$ implement属性中。
另外,应定义$ formConfig类属性,其值应引用用于配置行为选项的YAML文件。

namespace Acme\Blog\Controllers;

class Categories extends \Backend\Classes\Controller
{
   public $implement = ['Backend.Behaviors.FormController'];

   public $formConfig = 'form_config.yaml';
}

注意:通常,表单和列表行为在同一控制器中一起使用

配置表单行为

$formConfig 属性中引用的配置文件以YAML格式定义。
该文件应放置在控制器的views目录中。
下面是一个典型的表单行为配置文件的示例:

# ===================================
#  Form Behavior Config
# ===================================

name: Blog Category
form: $/acme/blog/models/post/fields.yaml
modelClass: Acme\Blog\Post

create:
    title: New Blog Post

update:
    title: Edit Blog Post

preview:
	title: View Blog Post

表单配置文件中必须包含以下字段:

字段描述
name此表单管理的对象的名称。
form配置数组或对表单域定义文件的引用,请参阅表单域(form fields)
modelClass模型类名称,针对此模型加载并保存表单数据。

下面列出的配置选项是可选的 如果您希望表单行为支持“创建”,“更新”或“预览”页面,请定义它们。

字段描述
defaultRedirect此表单管理的对象的名称。
create为 创建页面 配置数组或配置文件的引用
update为 更新页面 配置数组或配置文件的引用
preview为 预览页面 配置数组或配置文件的引用

创建page

要支持“创建”页面,请将以下配置添加到YAML文件:

create:
    title: New Blog Post
    redirect: acme/blog/posts/update/:id
    redirectClose: acme/blog/posts
    flashSave: Post has been created!

“创建”页面支持以下配置选项:

字段描述
title页面标题,可以引用本地化字符串(localization string.)
redirect保存记录时的重定向页面。
redirectClose记录被保存并且post变量close随着request发送后的重定向页面
flashSave保存记录时显示的Flash消息,可以引用本地化字符串。
form覆盖默认表单字段 仅限创建页面

升级page

要支持“更新”页面,请在YAML文件中添加以下配置:

update:
    title: Edit Blog Post
    redirect: acme/blog/posts
    flashSave: Post updated successfully!
    flashDelete: Post has been deleted.

“更新”页面支持以下配置选项:

字段描述
title页面标题,可以引用本地化字符串(localization string.)
redirect记录保存后重定向到哪里
redirectClose记录被保存并且post变量close随着request发送后的重定向页面
flashSave当记录被保存后的flash消息 可以做本地化处理
flashDelete当记录被删除后的flash消息 可以做本地化处理
form覆盖默认表单字段 仅限update页面

预览page

要支持“预览”页面,请在YAML文件中添加以下配置:

preview:
    title: View Blog Post

“预览”页面支持以下配置选项:

字段描述
title页面标题,可以引用本地化字符串(localization string.)
form覆盖默认表单字段 仅限preview页面

定义表单字段

表单字段是使用YAML文件定义的。
表单字段配置通过创建form controls并把他们绑定到model字段上
这个文件位于插件的model文件夹下的子文件夹
该子文件夹是小写的model类名组成
文件名无所谓,一般fields.yaml 或 form_fields.yaml是常用名称
例:

plugins/
  acme/
    blog/
      models/            <=== Plugin models directory
        post/            <=== Model configuration directory
          fields.yaml    <=== Model form fields config file
        Post.php         <=== model class

字段可以放在三个区域中,即外部区域,主选项卡或辅助选项卡。下一个示例显示表单字段定义文件的典型内容。

# ===================================
#  Form Field Definitions
# ===================================

fields:
    blog_title:
        label: Blog Title
        description: The title for this blog

    published_at:
        label: Published date
        description: When this blog post was published
        type: datepicker

    [...]

tabs:
    fields:
        [...]

secondaryTabs:
    fields:
        [...]

可以使用Relation Widget 或 the Relation Manager 呈现相关模型中的字段。
一个例外是OneToOne或morphOne相关字段,必须将其定义为related [field],然后可以将其指定为模型的任何其他字段:

  user_name:
        label: User Name
        description: The name of the user
    avatar[name]:
        label: Avatar
        description: will be saved in the Avatar table
    published_at:
        label: Published date
        description: When this blog post was published
        type: datepicker

    [...]

Tab options

对于每个选项卡定义,即tabs和secondaryTabs,可以指定以下选项:

字段描述
stretch指定此选项卡是否拉伸以适合父级高度。
defaultTab分配字段的默认标签。默认值:其他Misc。
icons使用选项卡名称作为键将图标分配给选项卡。
lazy单击时动态加载的选项卡数组。对于包含大量内容的选项卡很有用。
cssClass将CSS类分配给选项卡容器。
paneCssClass将CSS类分配给单个选项卡窗格。这是一个数组,键是制表符索引或标签,值是CSS类。也可以将其指定为字符串,在这种情况下,该值将应用于所有选项卡。
tabs:
    stretch: true
    defaultTab: User
    cssClass: text-blue
    lazy:
        - Groups
    paneCssClass:
        0: first-tab
        1: second-tab
    icons:
        User: icon-user
        Groups: icon-group

    fields:
        username:
            type: text
            label: Username
            tab: User

        groups:
            type: relation
            label: Groups
            tab: Groups

Field options

您可以为每个字段指定以下选项(如果适用):

选项描述
label向用户显示表单字段时的名称。
type定义应如何呈现此字段(请参见下面的“可用字段”类型)。默认值:文本text。
span将表单字段对齐到一侧。选项:auto, left, right, storm, full. 。默认值:full。参数storm使您可以使用cssClass属性将表单显示为Bootstrap网格,例如cssClass:col-xs-4。
size指定使用它的字段的字段大小,例如textarea字段。选项: tiny, small, large, huge, giant.
placeholder如果该字段支持占位符值。
comment在该字段下放置一个描述性注释。
comentAbove在字段上方添加评论。
commentHtml允许在注释内添加HTML标记。选项:true,false。
default指定该字段的默认值。
defaultFrom从另一个字段的值中获取默认值。
tab将字段分配给选项卡。
cssClass将CSS类分配给字段容器。
readOnly防止修改字段。选项:true,false。
disabled防止修改字段并将其从保存的数据中排除。选项:true,false。
hidden从视图中隐藏该字段,并将其从保存的数据中排除。选项:true,false。
stretch指定此字段是否拉伸以适合父级高度。
context指定显示字段时应使用的上下文。还可以通过在字段名称中使用@符号(例如,name@update)来传递上下文。
dependsOn此字段所依赖的其他字段名称的数组,当修改其他字段时,此字段将更新。
trigger使用trigger事件
preset允许该字段值初始化为另一个字段的值,并使用输入预设转换器( input preset converter)进行转换。
required在字段标签旁边放置一个红色星号以指示它是必需的(请确保在模型上设置验证,因为这不是由表单控制器强制执行的)。
attributes指定要添加到表单字段元素的自定义HTML属性。
containerAttributes指定要添加到表单字段容器的自定义HTML属性。
permissions当前后端用户必须具有的权限才能使用该字段。支持单个权限的字符串或仅需要一个权限即可授予访问权限的一组权限。

Available field types 字段类型汇总

type设置提供了很多预设的字段类型,所以我们制作了一个form小部件

  • Text
  • Number
  • Password
  • Email
  • Textarea
  • Dropdown
  • Radio List
  • Balloon Selector
  • Checkbox
  • Checkbox List
  • Switch
  • Section
  • Partial
  • Hint
  • Widget

text

text - 呈现单行文本框。如果未指定,则使用默认类型。

blog_title:
    label: Blog Title
    type: text

Number

number - 渲染仅接受数字的单行文本框。

your_age:
    label: Your Age
    type: number
    step: 1  # defaults to 'any'
    min: 1   # defaults to not present
    max: 100 # defaults to not present

如果您想在保存时在服务器端验证此字段以确保其为数字,请在模型上使用$ rules属性,如下所示:

/**
 * @var array Validation rules
 */
public $rules = [
    'your_age' => 'numeric',
];

有关模型验证的更多信息,请访问 the documentation page.

Password

password - 呈现单行密码字段。

user_password:
    label: Password
    type: password

Email

email - 呈现类型为email的单行文本框,从而触发移动浏览器中的电子邮件专用键盘。

user_email:
    label: Email Address
    type: email

如果您想在保存时验证此字段以确保它是格式正确的电子邮件地址,请在模型上使用$ rules属性,如下所示:

/**
 * @var array Validation rules
 */
public $rules = [
    'user_email' => 'email',
];

有关模型验证的更多信息,请访问 the documentation page.

Textarea

textarea - 呈现多行文本框。大小也可以用可能的值指定: tiny, small, large, huge, giant.

blog_contents:
    label: Contents
    type: textarea
    size: large

Dropdown

dropdown - 使用指定的选项呈现下拉菜单。有四种提供下拉选项的方法。第一种方法直接在YAML文件中定义options

status_type:
    label: Blog Post Status
    type: dropdown
    default: published
    options:
        draft: Draft
        published: Published
        archived: Archived

第二种方法使用在模型的类中声明的方法定义选项 如果省略options元素,则框架期望在模式下定义一个名为get * FieldName * Options的方法。使用上面的示例,模型应该具有getStatusTypeOptions方法。此方法的第一个参数是该字段的当前值,第二个参数是整个表单的当前数据对象。此方法应以** key => label **格式返回选项数组。

status_type:
    label: Blog Post Status
    type: dropdown

在模型类中提供下拉选项:

public function getStatusTypeOptions($value, $formData)
{
    return ['all' => 'All', ...];
}

还可以在模型中定义第三个全局方法“ getDropdownOptions”,该方法将用于模型的所有下拉字段类型。该方法的第一个参数是字段名称,第二个是字段的当前值,第三个是整个表单的当前数据对象。它应以** key => label **格式返回一组选项。

public function getDropdownOptions($fieldName, $value, $formData)
{
    if ($fieldName == 'status') {
        return ['all' => 'All', ...];
    }
    else {
        return ['' => '-- none --'];
    }
}

第四个方法使用在模型的类中声明的特定方法。在下一个示例中,应在模型类中定义listStatuses方法。此方法接收与getDropdownOptions方法相同的所有参数,并应以** key => label **格式返回选项数组。

status:
    label: Blog Post Status
    type: dropdown
    options: listStatuses

为模型类提供下拉选项:

public function listStatuses($fieldName, $value, $formData)
{
    return ['published' => 'Published', ...];
}

要定义没有选择时的行为,您可以指定“ emptyOption”值以包含可以重新选择的空选项。

status:
    label: Blog Post Status
    type: dropdown
    emptyOption: -- no status --

或者,您可以使用“占位符”选项来使用无法重新选择的“单向”空选项。

status:
    label: Blog Post Status
    type: dropdown
    placeholder: -- select a status --

默认情况下,下拉菜单具有搜索功能,可以快速选择一个值。可以通过将showSearch选项设置为false来禁用它。

status:
    label: Blog Post Status
    type: dropdown
    showSearch: false

Radio List

radio - 呈现单选选项列表,一次只能选择一项。

security_level:
    label: Access Level
    type: radio
    default: guests
    options:
        all: All
        registered: Registered only
        guests: Guests only

单选列表还可以支持辅助描述。

security_level:
    label: Access Level
    type: radio
    options:
        all: [All, Guests and customers will be able to access this page.]
        registered: [Registered only, Only logged in member will be able to access this page.]
        guests: [Guests only, Only guest users will be able to access this page.]

单选列表支持三种定义选项的方式,完全类似于[下拉字段类型](#field-dropdown)。
对于单选列表,该方法可以返回简单数组:key => value 或用于提供描述的数组数组:key => [label, description]
通过在Radio字段配置中指定cssClass:'inline-options',选项可以彼此内联显示,而不是单独显示。

Balloon Selector

balloon-selector - 呈现一个列表,一次只能选择一项。

gender:
    label: Gender
    type: balloon-selector
    default: female
    options:
        female: Female
        male: Male

气球选择器支持三种定义选项的方式,就像 dropdown field type.

Checkbox

checkbox - 呈现一个复选框。

show_content:
    label: Display content
    type: checkbox
    default: true

Checkbox List

checkboxlist -呈现复选框列表。

permissions:
    label: Permissions
    type: checkboxlist
    # set to true to explicitly enable the "Select All", "Select None" options
    # on lists that have <=10 items (>10 automatically enables it)
    quickselect: true
    default: open_account
    options:
        open_account: Open account
        close_account: Close account
        modify_account: Modify account

复选框列表支持三种定义选项的方式,就像 dropdown field type
并且像radio一样支持辅助说明 radio field type.
通过在复选框列表字段配置中指定`cssClass:‘inline-options’,可以将选项彼此内联显示,而不是单独显示。

Switch

switch - switchbox.

show_content:
    label: Display content
    type: switch
    comment: Flick this switch to display content
    on: myauthor.myplugin::lang.models.mymodel.show_content.on
    off: myauthor.myplugin::lang.models.mymodel.show_content.off

Section

section - 呈现节标题和副标题。 “ label”和“ comment”值是可选的,并且包含标题和子标题的内容。

user_details_section:
    label: User details
    type: section
    comment: This section contains details about the user.

Partial

partial - 呈现partial,“ path”值可以引用部分视图文件,否则将字段名称用作部分名称。在部分变量中,这些变量可用:$ value是默认字段值, `$ model是用于字段的模型,$ field是已配置的类对象Backend\Classes\FormField.

content:
    type: partial
    path: $/acme/blog/models/comments/_content_field.htm

Hint

hint - 与partial字段相同,但在提示容器内部呈现,用户可以将其隐藏。

content:
    type: hint
    path: content_field

Widget

widget - 呈现自定义表单窗口小部件,“type”字段可以直接引用窗口小部件的类名或注册的别名。

blog_content:
    type: Backend\FormWidgets\RichEditor
    size: huge

Form widgets

尽管插件会提供定制化的表单小部件,不过我们还是提供了很多的标准小部件。
你可以通过 Form Widgets 文章了解它们.

Code editor

codeeditor - 呈现用于格式代码或标记的纯文本编辑器。请注意,这些选项可以由后端为管理员定义的代码编辑器首选项继承。

css_content:
    type: codeeditor
    size: huge
    language: html
OptionDescription
language代码语言 如 php, css, js, html. 缺省: php.
showGutter显示带有行号的gutter. Default: true.
wrapWords折行. Default true.
fontSize字体. Default: 12.

Color picker

colorpicker - 十六位颜色选择控件

color:
    label: Background
    type: colorpicker
OptionDescription
availableColors可用颜色列表.
allowEmpty允许输入值为空。 Default: false

有两种方法可以为选色器提供可用的颜色。第一种方法将“ availableColors”直接定义为YAML文件中的十六进制颜色代码列表:

color:
    label: Background
    type: colorpicker
    availableColors: ['#000000', '#111111', '#222222']

第二种方法使用在模型的类中声明的特定方法。
此方法应以与上述示例相同的格式返回十六进制颜色的数组。
此方法的第一个参数是字段名称,第二个参数是字段的当前值,第三个参数是整个表单的当前数据对象。

color:
    label: Background
    type: colorpicker
    availableColors: myColorList

在模型类中提供可用的颜色:

public function myColorList($fieldName, $value, $formData)
{
    return ['#000000', '#111111', '#222222']
}

如果未在YAML文件中定义“ availableColors”字段,则颜色选择器将使用一组20种默认颜色。

Data table

datatable - 呈现可编辑的记录表,格式为grid。单元格内容可以直接在grid中进行编辑,从而可以管理几行和几列信息。

注意: 为了在模型中使用此字段,应将字段定义为jsonable属性或另一个可以处理存储数组数据的属性。

data:
    type: datatable
    adding: true
    btnAddRowLabel: Add Row Above
    btnAddRowBelowLabel: Add Row Below
    btnDeleteRowLabel: Delete Row
    columns: []
    deleting: true
    dynamicHeight: true
    fieldName: null
    height: false
    keyFrom: id
    recordsPerPage: false
    searching: false
    toolbar: []
Table configuration

以下列出了数据表窗口小部件本身的配置值

配置描述
adding允许将记录添加到数据表. Default: true.
btnAddRowLabel为“在上方添加行”按钮定义自定义标签。
btnAddRowBelowLabel为“在下面添加行”按钮定义自定义标签。
btnDeleteRowLabel为“删除行”按钮定义自定义标签。
columns表示数据表的列配置的数组。请参阅下面的“列配置”部分。
deleting允许从数据表中删除记录. Default: false.
dynamicHeight如果为“ true”,则数据表的高度将根据添加的记录而扩展或缩小,直到由“ height”配置值定义的最大大小. Default: false.
fieldName定义一个自定义字段名称,以在从数据表发送的POST数据中使用。保留空白以使用默认字段别名。
height数据表的高度(以像素为单位)。如果设置为“ false”,则数据表将拉伸以适合字段容器。
keyFrom用于键控每个记录的data属性。通常应将其设置为“ id”。
postbackHandlerName指定用于发送数据表内容的AJAX处理程序名称。当设置为“ null”(默认)时,处理程序名称将从包含数据表的表单所使用的请求名称中自动检测出来。建议将其保留为“ null”。
recordsPerPage每页显示的记录数。如果设置为“ false”,则分页将被禁用。
searching允许通过搜索框搜索记录。默认值:“ false”。
toolbar表示数据表的工具栏配置的数组。
Column configuration 列配置

数据表小部件允许通过“ columns”配置变量将列指定为数组。
每列应使用字段名称作为key,并使用以下配置变量来设置字段。

Example:

columns:
    id:
        type: string
        title: ID
        validation:
            integer:
                message: Please enter a number
    name:
        type: string
        title: Name
OptionDescription
type此列单元格的输入类型。必须是以下之一: string, checkbox, dropdown or autocomplete.
options仅适用于 dropdownautocomplete 列 - this specifies the AJAX handler that will return the available options, as an array. The array key is used as the value of the option, and the array value is used as the option label.这指定了将以数组形式返回可用选项的AJAX方法。数组key是option的值,value是选项标签。
readOnly此列是否为只读。. Default: false.
title定义列的标题。
validation一个数组,用于指定对列单元格内容的验证。请参阅下面的“列验证”部分。
width定义列的宽度(以像素为单位)。
Column validation

可以根据以下验证类型来验证列单元格。
验证应指定为一个数组,其key是验证类型,并为该验证指定一个可选消息作为message属性。

ValidationDescription
float作为浮点数验证data 可选属性 allowNegetive 是布尔值,是否同意负浮点数
integer将数据验证为整数。 可以提供可选的booleanallowNegative属性,允许使用负整数。
length验证数据长度。必须提供整数“ min”和“ max”属性,代表必须输入的最小和最大字符数。
regex根据正则表达式验证数据。必须提供一个字符串“ pattern”属性,该属性定义用于测试数据的正则表达式。
required验证在保存之前必须输入数据。

Date picker

datepicker - 日历

published_at:
    label: Published
    type: datepicker
    mode: date
OptionDescription
mode预期的结果,date, datetime 或 time. Default: datetime.
format提供明确的日期显示格式 Eg: Y-m-d
minDate可以选择的最短/最早日期 Default: 2000-01-01.
maxDate可以选择的最大/最新日期。Default: 2020-12-31.
firstDay一周的第一天。 Default: 0 (Sunday).
showWeekNumber在行首显示星期数。. Default: false
ignoreTimezone完全按照显示的日期和时间存储日期和时间,而忽略后端指定的时区首选项。

File upload

fileupload - 文件上传 字段名称必须使用attachOne或attachMany关系

avatar:
    label: Avatar
    type: fileupload
    mode: image
    imageHeight: 260
    imageWidth: 260
    thumbOptions:
        mode: crop
        offset:
            - 0
            - 0
        quality: 90
        sharpen: 0
        interlace: false
        extension: auto
OptionDescription
mode预期的文件类型,文件或图像. Default: image.
imageWidth如果使用图像类型,图像将被调整为该宽度,可选。
imageHeight如果使用图像类型,则图像将被调整为该高度,可选。
fileTypes上传者接受的文件扩展名(可选)。 Eg: zip,txt
mimeTypes上载者接受的MIME类型,可以是文件扩展名或完全限定名称(可选)。Eg: bin,txt
maxFilesize上载者接受的文件大小(Mb),可选。Default: 从"upload_max_filesize" 参数读取
useCaption允许为文件设置标题和描述. Default: true
prompt为上载按钮显示的文本,仅适用于文件,可选。
thumbOptions传递给文件的缩略图生成方法的选项
attachOnUpload如果存在父记录,则在上传时自动附加上载的文件,而不是使用延迟绑定在保存父记录时附加。默认为false

Markdown editor

markdown - 呈现降价格式文本的基本编辑器。

md_content:
    type: markdown
    size: huge
    mode: split
OptionDescription
modethe expected view mode, either tab or split. Default: tab.

Media finder

mediafinder - 呈现一个用于从媒体管理器库中选择项目的字段。展开该字段将显示媒体管理器以找到文件。结果选择是作为文件相对路径的一个字符串。

background_image:
    label: Background image
    type: mediafinder
    mode: image
OptionDescription
mode预期的文件类型, file 或 image. Default: file.
prompt未选择任何项目时显示的文本. %s 代表媒体管理器图标。
imageWidth如果使用图像类型,则预览图像将以该宽度显示(可选)。
imageHeight如果使用图像类型,则预览图像将以该高度显示(可选)。

Note: 不同于 File Upload form widget, Media Finder表单小部件将其数据存储为一个字符串,该字符串表示在媒体库中选择的图像的路径。

Nested Form

nestedform - 将嵌套形式呈现为该字段的内容,并以包含的字段的数组形式返回数据。

NOTE: 为了在模型中使用此字段,应将字段定义为jsonable属性或另一个可以处理存储数组数据的属性。

content:
    type: nestedform
    usePanelStyles: false
    form:
        fields:
            added_at:
                label: Date added
                type: datepicker
            details:
                label: Details
                type: textarea
            title:
                label: This the title
                type: text
        tabs:
            meta_title:
                lable: Meta Title
                tab: SEO
            color:
                label: Color
                type: colorpicker
                tab: Design
        secondaryTabs:
            is_active:
                label: Active
                type: checkbox
            logo:
                label: Logo
                type: mediafinder
                mode: image

嵌套表单支持与表单本身相同的语法,包括tab和secondaryTabs。 jsonsable属性具有表单定义的结构。甚至有可能在嵌套表单中使用嵌套表单。

OptionDescription
formform definition一样
usePanelStyles定义是否应用外观类似的面板(默认为true)

Record finder

recordfinder
呈现一个包含关联record详细信息的字段。
展开该字段将显示一个弹出列表,以搜索大量记录。
仅单数关系支持。

user:
    label: User
    type: recordfinder
    list: ~/plugins/rainlab/user/models/user/columns.yaml
    recordsPerPage: 10
    title: Find Record
    prompt: Click the Find button to find a user
    keyFrom: id
    nameFrom: name
    descriptionFrom: email
    conditions: email = "bob@example.com"
    scope: whereActive
    searchMode: all
    searchScope: searchUsers
    useRelation: false
    modelClass: RainLab\User\Models\User
OptionDescription
keyFrom在用于key的关系中使用的列的名称。Default: id.
nameFrom在用于显示名称的关系中使用的列名称。 Default: name.
descriptionFrom在用于显示描述的关系中使用的列名。 Default: description.
title文本显示在弹出窗口的标题部分。
prompt没有选择记录时显示的文本。 “%s”字符代表搜索图标。
list配置数组或对列表列定义文件的引用, 请看 list columns.
recordsPerPage每页显示的记录数,没有页数请使用0。 Default: 10
conditions指定要应用于列表模型查询的原始where查询语句。
scope指定在“相关表单模型related form model”中定义的查询范围方法query scope method ,始终用于列表查询,第一个参数包含一个model,里面attach小部件的值。即父model。
searchMode将搜索策略定义为包含所有单词,任何单词或确切短语。支持的选项: all, any, exact. Default: all.
searchScope指定一个定义在 related form model中的 query scope method用于提交搜索请求, 第一个参数包含搜索词
useRelation一个flag标识,用于将字段名称用作关系名称以直接在父模型上进行交互。默认值:true。禁用仅返回所选model的ID
modelClassuseRelation = false时用于列出记录的模型的类

Relation

relation - 根据字段关系类型呈现下拉列表或复选框列表。
一对一显示一个下拉列表,一对多多对多显示一个复选框列表。
用于显示每个关系的标签来自 nameFromselect 定义。

categories:
    label: Categories
    type: relation
    nameFrom: title

或者,您可以使用自定义的select 语句填充标签。任何有效的SQL语句在这里都有效。

user:
    label: User
    type: relation
    select: concat(first_name, ' ', last_name)

You can also provide a model scope to use to filter the results with the scope property.
你还可以提供模型作用域model scope,以使用scope属性过滤结果。

OptionDescription
nameFrom用于显示关系标签的model属性名称。.Default: name.
select用于名称的自定义SQL select语句。
order用于对选项进行排序的order子句. Example: name desc.
emptyOption没有可用选择时显示的文本
scope指定一个定义在related form model中的query scope method ,始终应用于列表查询

Repeater

repeater - 呈现其中定义的一组重复的表单字段。

extra_information:
    type: repeater
    titleFrom: title_when_collapsed
    form:
        fields:
            added_at:
                label: Date added
                type: datepicker
            details:
                label: Details
                type: textarea
            title_when_collapsed:
                label: This field is the title when collapsed
                type: text
OptionDescription
form对表单字段定义文件的引用, 请看 backend form fields. 也可以内联使用
prompt用于创建按钮显示的文本. Default: Add new item.
titleFrom项目中用作折叠项目标题的字段名称。
minItems最少显示条目数。不使用组时预显示这些项目。例如,如果您设置 ‘minItems: 1’ ,则第一行将显示而不是隐藏。
maxItemsrepeater中允许显示的最大条目数
groups组模式下把一组相关字段放在repeater中(见下).也可以内联使用
stylerepeater条目展现形式 能用的有: default, collapsed or accordion. 参见 Repeater styles

转发器字段支持分组模式,该模式允许为每次迭代选择一组自定义字段。

content:
    type: repeater
    prompt: Add content block
    groups: $/acme/blog/config/repeater_fields.yaml

这是一个组配置文件的示例,该文件位于 /plugins/acme/blog/config/repeater_fields.yaml. 另外,这些定义可以在转发器内联指定。

textarea:
    name: Textarea
    description: Basic text field
    icon: icon-file-text-o
    fields:
        text_area:
            label: Text Content
            type: textarea
            size: large

quote:
    name: Quote
    description: Quote item
    icon: icon-quote-right
    fields:
        quote_position:
            span: auto
            label: Quote Position
            type: radio
            options:
                left: Left
                center: Center
                right: Right
        quote_content:
            span: auto
            label: Details
            type: textarea

每个组必须指定一个唯一键,并且该定义支持以下选项。

OptionDescription
name组名.
description简短描述.
icon图标 可选
fields该组表单字段, 参见 backend form fields.

Note: 组密钥与保存的数据一起存储为 _group 属性

Repeater styles

转发器小部件的styles 属性控制转发器项目的行为。开发人员可以使用三种不同类型的样式:

  • default: 展开展示所有条目
  • collapsed: 初始时都折叠,用户自己展开或折叠
  • accordion: 初始第一个打开其他折叠 每次只能展开一个

Rich editor / WYSIWYG

richeditor - WYSIWYG编辑器

html_content:
    type: richeditor
    toolbarButtons: bold|italic
    size: huge
OptionDescription
toolbarButtons在编辑器工具栏上显示哪些按钮。

可用的工具栏按钮为:

fullscreen, bold, italic, underline, strikeThrough, subscript, superscript, fontFamily, fontSize, |, color, emoticons, inlineStyle, paragraphStyle, |, paragraphFormat, align, formatOL, formatUL, outdent, indent, quote, insertHR, -, insertLink, insertImage, insertVideo, insertAudio, insertFile, insertTable, undo, redo, clearFormatting, selectAll, html

Note: | will insert a vertical separator line in the toolbar and - a horizontal one.

Tag list

taglist—呈现一个用于输入标记列表的字段。

tags:
    type: taglist
    separator: space

标记列表可以支持三种定义option的方法,与dropdown field type完全一样。

tags:
    type: taglist
    options:
        - Red
        - Blue
        - Orange

您可以使用 mode:relationship,其中字段名是[多对多关系]。并通过此标记自动分配关系。如果支持自定义标记,则将在分配之前创建它们。

tags:
    type: taglist
    mode: relation
OptionDescription
mode控制返回值, string, array 或 relation. Default: string
separator用逗号还是空格分隔tags. Default: comma
customTags允许用户手动输入自定义标签 Default: true
options指定预定义选项的方法或数组 设置true则用model get*Field*Options 方法. 可选.
nameFrom如果relation mode已经设置, 用于显示标签名称的模型属性名称。. Default: name
useKey使用键而不是值来保存和读取数据 Default: false

Form views

表单页面支持[创建],[更新]和[预览],都提供了view页面,并具有相应的名称-create.htmupdate.htmpreview.htm

表单行为向控制器类添加了两个方法:formRender和formRenderPreview。这些方法呈现使用上述YAML文件配置的表单控件。


###创建视图

create.htm视图表示创建页面,该页面允许用户创建新记录。典型的“创建”页面包含面包屑,表单本身和表单按钮。数据请求属性应引用表单行为提供的onSave AJAX处理程序。以下是典型的create.htm表单的内容。

<?= Form::open(['class'=>'layout']) ?>

    <div class="layout-row">
        <?= $this->formRender() ?>
    </div>

    <div class="form-buttons">
        <div class="loading-indicator-container">
            <button
                type="button"
                data-request="onSave"
                data-request-data="close:true"
                data-hotkey="ctrl+enter, cmd+enter"
                data-load-indicator="Creating Category..."
                class="btn btn-default">
                Create and Close
            </button>
            <span class="btn-text">
                or <a href="<?= Backend::url('acme/blog/categories') ?>">Cancel</a>
            </span>
        </div>
    </div>

<?= Form::close() ?>


###更新视图

** update.htm **视图表示“更新”页面,该页面允许用户更新或删除现有记录。典型的“更新”页面包含面包屑,表单本身和表单按钮。 “更新”页面与“创建”页面非常相似,但通常具有“删除”按钮。数据请求属性应引用表单行为提供的onSave AJAX处理程序。以下是典型的update.htm表单的内容。

<?= Form::open(['class'=>'layout']) ?>

    <div class="layout-row">
        <?= $this->formRender() ?>
    </div>

    <div class="form-buttons">
        <div class="loading-indicator-container">
            <button
                type="button"
                data-request="onSave"
                data-request-data="close:true"
                data-hotkey="ctrl+enter, cmd+enter"
                data-load-indicator="Saving Category..."
                class="btn btn-default">
                Save and Close
            </button>
            <button
                type="button"
                class="oc-icon-trash-o btn-icon danger pull-right"
                data-request="onDelete"
                data-load-indicator="Deleting Category..."
                data-request-confirm="Do you really want to delete this category?">
            </button>
            <span class="btn-text">
                or <a href="<?= Backend::url('acme/blog/categories') ?>">Cancel</a>
            </span>
        </div>
    </div>

<?= Form::close() ?>


###预览视图

** preview.htm **视图表示“预览”页面,该页面允许用户以只读模式预览现有记录。典型的“预览”页面包含面包屑和表单本身。下面是典型的Preview.htm表单的内容。

<div class="form-preview">
    <?= $this->formRenderPreview() ?>
</div>

Applying conditions to fields 将条件应用于字段

有时,您可能希望在某些条件下操纵表单字段的值或外观
例如,如果勾选了复选框,则可能希望隐藏input。您可以通过触发器API或字段依赖项来执行此操作。
输入预设转换器The input preset converter主要用于转换字段值。
这些选项将在下面更详细地描述。

Input preset converter 输入预设转换器

输入预设转换器是通过`preset’form field option定义的,它允许您将输入到元素中的文本转换为另一个输入元素中的URL,段或文件名值

在此示例中,当用户在title字段中输入文本时,我们将自动填写url字段值。如果在标题中输入文本Hello world,则URL将跟着转换后的值**/hello-world**。仅当目标字段(url)为空且未更改时,才会发生此行为

title:
    label: Title

url:
    label: URL
    preset:
        field: title
        type: url

另外,preset值也可以是仅引用field的字符串,type选项将默认为slug

slug:
    label: Slug
    preset: title

以下选项可用于preset选项:

OptionDescription
field定义另一个字段名称来作为值的来源。
type指定转换类型。请参阅下面的支持表。
prefixInput选,使用CSS选择器在转换后的值之前提供在提供的输入元素中找到的值。

以下是受支持类型:

TypeDescription
exact复制准确值
slug将值slug化
urlslug化 前面加/
camel复制的值变为驼峰法格式
file将复制的值格式化为文件名,并用短划线代替空格

Trigger events 触发事件

触发器事件是用trigger form field option 定义的,是一个使用JavaScript的简单基于浏览器的解决方案。
它允许您根据其他元素的状态更改元素属性,如可见性或值。
下面是一个示例定义:

is_delayed:
    label: Send later
    comment: Place a tick in this box if you want to send this message at a later time.
    type: checkbox

send_at:
    label: Send date
    type: datepicker
    cssClass: field-indent
    trigger:
        action: show
        field: is_delayed
        condition: checked

In the above example the send_at form field will only be shown if the is_delayed field is checked. In other words, the field will show (action) if the other form input (field) is checked (condition). The trigger definition specifies these options:
在上面的示例中,只有选中“is_delayed”字段,才会显示“send_at”表单字段。
换句话说,如果其他表单input (字段field) 被checked (条件condition).,则该字段将show (动作action) 。“trigger”定义指定以下选项:

OptionDescription
action定义满足条件时应用于此字段的操作. 支持的值: show, hide, enable, disable, empty.
field定义将触发该操作的其他字段名。通常字段名指的是同一级别表单中的字段。例如,如果该字段在repeater widget中,则只检查同一repeater widget中的字段。但是,如果字段名前面有一个插入符号^如:^parent_field,它将引用比字段本身更高一级repeater widget或表单。另外,如果使用了多个插入符号^,它将引用更高的级别:^^grand_parent_field^^^grand_grand_grand_parent_field,等等。
condition确定指定字段应满足的条件,才能将条件视为“ true”。Supported values: checked, unchecked, value[somevalue].

Field dependencies 字段依赖

表单字段可以通过定义 dependsOn form field option 来声明对其他字段的依赖关系,该字段提供了更健壮的服务器端解决方案,用于在修改其依赖关系时更新字段。
当声明为依赖项的字段发生更改时,定义字段将使用AJAX框架进行更新。
他提供了使用filterFields方法或更改要提供给该字段的可用选项与该字段的属性进行交互的机会。
例子

country:
    label: Country
    type: dropdown

state:
    label: State
    type: dropdown
    dependsOn: country

在上面的示例中,当“国家”字段的值更改时,“状态”表单字段将刷新。发生这种情况时,当前表单数据将被填充到model中,以便下拉选项可以使用它。

public function getCountryOptions()
{
    return ['au' => 'Australia', 'ca' => 'Canada'];
}

public function getStateOptions()
{
    if ($this->country == 'au') {
        return ['act' => 'Capital Territory', 'qld' => 'Queensland', ...];
    }
    elseif ($this->country == 'ca') {
        return ['bc' => 'British Columbia', 'on' => 'Ontario', ...];
    }
}

该示例对于处理模型值很有用,但无权访问表单字段定义。
您可以通过在模型内部定义一个filterFields方法来过滤表单字段, Filtering form fields 中做了介绍
例子:

dnsprovider:
    label: DNS Provider
    type: dropdown

registrar:
    label: Registrar
    type: dropdown

specificfields[for][provider1]:
    label: Provider 1 ID
    type: text
    hidden: true
    dependsOn:
        - dnsprovider
        - registrar

specificfields[for][provider2]:
    label: Provider 2 ID
    type: text
    hidden: true
    dependsOn:
        - dnsprovider
        - registrar

filterFields方法的逻辑如下:

public function filterFields($fields, $context = null)
{
    $displayedVendors = strtolower($this->dnsprovider->name . $this->registrar->name);
    if (str_contains($displayedVendors, 'provider1')) {
        $fields->{'specificfields[for][provider1]'}->hidden = false;
    }
    if (str_contains($displayedVendors, 'provider2')) {
        $fields->{'specificfields[for][provider2]'}->hidden = false;
    }
}

在上面的示例中,provider1provider2字段都将在dnsproviderregistrar`字段被修改时自动刷新。
发生这种情况时,将处理完整的表单循环,这意味着在“filterFields”方法中定义的任何逻辑都将再次运行,从而允许你筛选动态显示的字段

Preventing a field from being submitted 阻止提交字段

有时您可能需要阻止提交字段。
为此,只需在表单配置文件中的字段名称之前添加下划线(_) 。以下划线开头的表单域将自动清除,不再保存到模型中。

address:
    label: Title
    type: text

_map:
    label: Point your address on the map
    type: mapviewer

Extending form behavior 扩展表单行为

有时您可能希望修改默认的表单行为
有几种方法可以执行此操作。

Overriding controller action 覆写controller action

You can use your own logic for the create, update or preview action method in the controller, then optionally call the Form behavior parent method.
您可以对控制器中的 create, updatepreview操作方法使用自己的逻辑,然后有选择地调用“表单行为”父方法

public function update($recordId, $context = null)
{
    //
    // 在这里写定制化代码
    //

    // 调用 FormController behavior update() 方法
    return $this->asExtension('FormController')->update($recordId, $context);
}

Overriding controller redirect 覆写controller 重定向

您可以通过覆盖formGetRedirectUrl方法来指定保存模型后重定向到的URL。
此方法返回将重定向到的位置,并将相对URL视为后端URL。

public function formGetRedirectUrl($context = null, $model = null)
{
    return 'https://octobercms.com';
}

Extending model query 扩展model query

可以通过覆盖控制器类内部的formExtendQuery方法来扩展对database model形式的查询。
下例将确保仍可以找到和更新软删除的记录:

public function formExtendQuery($query)
{
    $query->withTrashed(); //通过将**withTrashed**范围应用于查询
}

Extending form fields 扩展表单字段

您可以通过在控制器类上调用extendFormFields静态方法来从外部扩展另一个控制器的字段。
此方法可以接受三个参数
f o r m ∗ ∗ 将 代 表 表 单 小 部 件 对 象 , ∗ ∗ form** 将代表表单小部件对象,** formmodel 代表表单使用的模型,$context是包含表单上下文的字符串。
例子:

class Categories extends \Backend\Classes\Controller
{
    public $implement = ['Backend.Behaviors.FormController'];

    public $formConfig = 'config_form.yaml';
}

使用extendFormFields方法,您可以向此控制器呈现的任何表单添加额外的字段。
由于这可能会影响此控制器使用的所有表格,因此最好检查**$model** 类型是否正确。

Categories::extendFormFields(function($form, $model, $context)
{
    if (!$model instanceof MyModel) {
        return;
    }

    $form->addFields([
        'my_field' => [
            'label'   => 'My Field',
            'comment' => 'This is a custom field I have added.',
        ],
    ]);

});

您还可以通过覆盖控制器类内部的formExtendFields方法在内部扩展表单字段。
这只会影响FormController 行为所使用的表单。

class Categories extends \Backend\Classes\Controller
{
    [...]

    public function formExtendFields($form)
    {
        $form->addFields([...]);
    }
}

$form对象方法如下.

MethodDescription
addFields将新字段添加到外部区域
addTabFields将新字段添加到选项卡式区域
addSecondaryTabFields将新字段添加到辅助选项卡式区域
removeField从任意区域删除字段

每种方法都采用类似于form field configuration的表单数组。

Filtering form fields 过滤表单字段

你可以通过覆写所用模型中的filterFields方法来过滤表单字段定义。
这使你可以根据模型数据操纵可见性和其他字段属性。
该方法带有两个参数
$fields表示 field configuration 已定义的字段的对象,而** $ context **表示活动表单上下文。

public function filterFields($fields, $context = null)
{
    if ($this->source_type == 'http') {
        $fields->source_url->hidden = false;
        $fields->git_branch->hidden = true;
    }
    elseif ($this->source_type == 'git') {
        $fields->source_url->hidden = false;
        $fields->git_branch->hidden = false;
    }
    else {
        $fields->source_url->hidden = true;
        $fields->git_branch->hidden = true;
    }
}

上面的示例将通过检查Model属性source_type的值在某些字段上设置hidden标志。
第一次加载表单时,以及通过 defined field dependency更新时,将应用此逻辑。

Validating form fields 验证表单字段

要验证表单的字段,可以使用模型中的Validation 某些用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值