文章目录

  • 表单
    • 介绍
    • 配置表单行为
      • 创建page
      • 升级page
      • 预览page
    • 定义表单字段
      • Tab options
      • Field options
    • Available field types 字段类型汇总
      • text
      • Number
      • Password
      • Email
      • Textarea
      • Dropdown
      • Radio List
      • Balloon Selector
      • Checkbox
      • Checkbox List
      • Switch
      • Section
      • Partial
      • Hint
      • Widget
    • Form widgets
      • Code editor
      • Color picker
      • Data table
        • Table configuration
        • Column configuration 列配置
        • Column validation
      • Date picker
      • File upload
      • Markdown editor
      • Media finder
      • Nested Form
      • Record finder
      • Relation
      • Repeater
        • Repeater styles
      • Rich editor / WYSIWYG
      • Tag list
    • Form views
    • Applying conditions to fields 将条件应用于字段
      • Input preset converter 输入预设转换器
      • Trigger events 触发事件
      • Field dependencies 字段依赖
      • Preventing a field from being submitted 阻止提交字段
    • Extending form behavior 扩展表单行为
      • Overriding controller action 覆写controller action
      • Overriding controller redirect 覆写controller 重定向
      • Extending model query 扩展model query
      • Extending form fields 扩展表单字段
      • Filtering form fields 过滤表单字段
    • Validating form fields 验证表单字段

表单

介绍

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\Postcreate:title: New Blog Postupdate:title: Edit Blog Postpreview:title: View Blog Post

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

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

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

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

创建page

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

create:title: New Blog Postredirect: acme/blog/posts/update/:idredirectClose: acme/blog/postsflashSave: Post has been created!

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

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

升级page

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

update:title: Edit Blog Postredirect: acme/blog/postsflashSave: 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 directorypost/            <=== Model configuration directoryfields.yaml    <=== Model form fields config filePost.php         <=== model class

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

# ===================================
#  Form Field Definitions
# ===================================fields:blog_title:label: Blog Titledescription: The title for this blogpublished_at:label: Published datedescription: When this blog post was publishedtype: datepicker[...]tabs:fields:[...]secondaryTabs:fields:[...]

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

  user_name:label: User Namedescription: The name of the useravatar[name]:label: Avatardescription: will be saved in the Avatar tablepublished_at:label: Published datedescription: When this blog post was publishedtype: datepicker[...]

Tab options

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

字段 描述
stretch 指定此选项卡是否拉伸以适合父级高度。
defaultTab 分配字段的默认标签。默认值:其他Misc。
icons 使用选项卡名称作为键将图标分配给选项卡。
lazy 单击时动态加载的选项卡数组。对于包含大量内容的选项卡很有用。
cssClass 将CSS类分配给选项卡容器。
paneCssClass 将CSS类分配给单个选项卡窗格。这是一个数组,键是制表符索引或标签,值是CSS类。也可以将其指定为字符串,在这种情况下,该值将应用于所有选项卡。
tabs:stretch: truedefaultTab: UsercssClass: text-bluelazy:- GroupspaneCssClass:0: first-tab1: second-tabicons:User: icon-userGroups: icon-groupfields:username:type: textlabel: Usernametab: Usergroups:type: relationlabel: Groupstab: 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 Titletype: text

Number

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

your_age:label: Your Agetype: numberstep: 1  # defaults to 'any'min: 1   # defaults to not presentmax: 100 # defaults to not present

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

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

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

Password

password - 呈现单行密码字段。

user_password:label: Passwordtype: password

Email

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

user_email:label: Email Addresstype: email

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

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

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

Textarea

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

blog_contents:label: Contentstype: textareasize: large

Dropdown

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

status_type:label: Blog Post Statustype: dropdowndefault: publishedoptions:draft: Draftpublished: Publishedarchived: Archived

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

status_type:label: Blog Post Statustype: 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 Statustype: dropdownoptions: listStatuses

为模型类提供下拉选项:

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

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

status:label: Blog Post Statustype: dropdownemptyOption: -- no status --

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

status:label: Blog Post Statustype: dropdownplaceholder: -- select a status --

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

status:label: Blog Post Statustype: dropdownshowSearch: false

Radio List

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

security_level:label: Access Leveltype: radiodefault: guestsoptions:all: Allregistered: Registered onlyguests: Guests only

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

security_level:label: Access Leveltype: radiooptions: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: Gendertype: balloon-selectordefault: femaleoptions:female: Femalemale: Male

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

Checkbox

checkbox - 呈现一个复选框。

show_content:label: Display contenttype: checkboxdefault: true

Checkbox List

checkboxlist -呈现复选框列表。

permissions:label: Permissionstype: checkboxlist# set to true to explicitly enable the "Select All", "Select None" options# on lists that have <=10 items (>10 automatically enables it)quickselect: truedefault: open_accountoptions:open_account: Open accountclose_account: Close accountmodify_account: Modify account

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

Switch

switch - switchbox.

show_content:label: Display contenttype: switchcomment: Flick this switch to display contenton: myauthor.myplugin::lang.models.mymodel.show_content.onoff: myauthor.myplugin::lang.models.mymodel.show_content.off

Section

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

user_details_section:label: User detailstype: sectioncomment: This section contains details about the user.

Partial

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

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

Hint

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

content:type: hintpath: content_field

Widget

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

blog_content:type: Backend\FormWidgets\RichEditorsize: huge

Form widgets

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

  • Code editor
  • Color picker
  • Data table
  • Date picker
  • File upload
  • Markdown editor
  • Media finder
  • Nested Form
  • Record finder
  • Relation
  • Repeater
  • Rich editor / WYSIWYG
  • Tag list

Code editor

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

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

Color picker

colorpicker - 十六位颜色选择控件

color:label: Backgroundtype: colorpicker
Option Description
availableColors 可用颜色列表.
allowEmpty 允许输入值为空。 Default: false

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

color:label: Backgroundtype: colorpickeravailableColors: ['#000000', '#111111', '#222222']

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

color:label: Backgroundtype: colorpickeravailableColors: myColorList

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

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

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

Data table

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

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

data:type: datatableadding: truebtnAddRowLabel: Add Row AbovebtnAddRowBelowLabel: Add Row BelowbtnDeleteRowLabel: Delete Rowcolumns: []deleting: truedynamicHeight: truefieldName: nullheight: falsekeyFrom: idrecordsPerPage: falsesearching: falsetoolbar: []

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: stringtitle: IDvalidation:integer:message: Please enter a numbername:type: stringtitle: Name
Option Description
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属性。

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

Date picker

datepicker - 日历

published_at:label: Publishedtype: datepickermode: date
Option Description
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: Avatartype: fileuploadmode: imageimageHeight: 260imageWidth: 260thumbOptions:mode: cropoffset:- 0- 0quality: 90sharpen: 0interlace: falseextension: auto
Option Description
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: markdownsize: hugemode: split
Option Description
mode the expected view mode, either tab or split. Default: tab.

Media finder

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

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

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

Nested Form

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

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

content:type: nestedformusePanelStyles: falseform:fields:added_at:label: Date addedtype: datepickerdetails:label: Detailstype: textareatitle:label: This the titletype: texttabs:meta_title:lable: Meta Titletab: SEOcolor:label: Colortype: colorpickertab: DesignsecondaryTabs:is_active:label: Activetype: checkboxlogo:label: Logotype: mediafindermode: image

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

Option Description
form 跟form definition一样
usePanelStyles 定义是否应用外观类似的面板(默认为true)

Record finder

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

user:label: Usertype: recordfinderlist: ~/plugins/rainlab/user/models/user/columns.yamlrecordsPerPage: 10title: Find Recordprompt: Click the Find button to find a userkeyFrom: idnameFrom: namedescriptionFrom: emailconditions: email = "bob@example.com"scope: whereActivesearchMode: allsearchScope: searchUsersuseRelation: falsemodelClass: RainLab\User\Models\User
Option Description
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
modelClass useRelation = false时用于列出记录的模型的类

Relation

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

categories:label: Categoriestype: relationnameFrom: title

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

user:label: Usertype: relationselect: 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属性过滤结果。

Option Description
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: repeatertitleFrom: title_when_collapsedform:fields:added_at:label: Date addedtype: datepickerdetails:label: Detailstype: textareatitle_when_collapsed:label: This field is the title when collapsedtype: text
Option Description
form 对表单字段定义文件的引用, 请看 backend form fields. 也可以内联使用
prompt 用于创建按钮显示的文本. Default: Add new item.
titleFrom 项目中用作折叠项目标题的字段名称。
minItems 最少显示条目数。不使用组时预显示这些项目。例如,如果您设置 ‘minItems: 1’ ,则第一行将显示而不是隐藏。
maxItems repeater中允许显示的最大条目数
groups 组模式下把一组相关字段放在repeater中(见下).也可以内联使用
style repeater条目展现形式 能用的有: default, collapsed or accordion. 参见 Repeater styles

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

content:type: repeaterprompt: Add content blockgroups: $/acme/blog/config/repeater_fields.yaml

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

textarea:name: Textareadescription: Basic text fieldicon: icon-file-text-ofields:text_area:label: Text Contenttype: textareasize: largequote:name: Quotedescription: Quote itemicon: icon-quote-rightfields:quote_position:span: autolabel: Quote Positiontype: radiooptions:left: Leftcenter: Centerright: Rightquote_content:span: autolabel: Detailstype: textarea

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

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

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

Repeater styles

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

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

Rich editor / WYSIWYG

richeditor - WYSIWYG编辑器

html_content:type: richeditortoolbarButtons: bold|italicsize: huge
Option Description
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: taglistseparator: space

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

tags:type: taglistoptions:- Red- Blue- Orange

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

tags:type: taglistmode: relation
Option Description
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"><buttontype="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"><buttontype="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><buttontype="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: Titleurl:label: URLpreset:field: titletype: url

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

slug:label: Slugpreset: title

以下选项可用于preset选项:

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

以下是受支持类型:

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

Trigger events 触发事件

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

is_delayed:label: Send latercomment: Place a tick in this box if you want to send this message at a later time.type: checkboxsend_at:label: Send datetype: datepickercssClass: field-indenttrigger:action: showfield: is_delayedcondition: 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”定义指定以下选项:

Option Description
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: Countrytype: dropdownstate:label: Statetype: dropdowndependsOn: 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 Providertype: dropdownregistrar:label: Registrartype: dropdownspecificfields[for][provider1]:label: Provider 1 IDtype: texthidden: truedependsOn:- dnsprovider- registrarspecificfields[for][provider2]:label: Provider 2 IDtype: texthidden: truedependsOn:- 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: Titletype: text_map:label: Point your address on the maptype: 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静态方法来从外部扩展另一个控制器的字段。
此方法可以接受三个参数
form∗∗将代表表单小部件对象,∗∗form** 将代表表单小部件对象,**form∗∗将代表表单小部件对象,∗∗model 代表表单使用的模型,$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对象方法如下.

Method Description
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 某些用法

October cms-Backend (后端-表单)相关推荐

  1. 迅睿CMS 创建网站表单

    网站表单性能和内容模块一样,支持百万级数据,附表按5万为基数自动分表. 网站表单可以做什么? 1.友情链接 2.用户留言 3.网站证书 4.在线订单(需配合交易系统) 5.在线报名 如何创建网站表单? ...

  2. 科汛CMS把自定义表单编辑器改成文章编辑器

    如果是前台提交 要给工具附加加功能可以直接在生成的模板代码中 加功能就或 相关功能见http://fex.baidu.com/ueditor/#start-toolbar 打开文件 admin\plu ...

  3. 动态表单工作量给后端

    动态表单工作量给后端 让前端远离互相伤害 一个IT公司的日常就是程序员.产品经理.UI等同事们的互相残杀: 应用,不少前端就备受煎熬,除了修改需求的魔咒外,还有后端的重构和调整接口诅咒,即便需求没改, ...

  4. JS同时上传表单图片和表单信息并把上传信息存入数据库,带php后端源码

    微信小程序开发交流qq群   581478349    承接微信小程序开发.扫码加微信. 利用JQ,jquery.form.js,bootstrap实现上传表单图片和表单信息并把上传的图片地址,inp ...

  5. Bootstrap4+MySQL前后端综合实训-Day08-PM【ajax获取表单标签内容、根据“栏目信息”添加“新闻信息”、新闻管理系统-项目展示】

    [Bootstrap4前端框架+MySQL数据库]前后端综合实训[10天课程 博客汇总表 详细笔记][附:实训所有代码] 目   录 ajax获取表单标签内容 ajax根据数据库加载select下来列 ...

  6. python中前后端通信方法Ajax和ORM映射(form表单提交)

    后端从数据库获取数据给到前端: 第一种方式: admin.py文件代码: @admin.route('/showList') def show():# 获取数据库所有文章数据,得到一个个对象res=A ...

  7. 后端的日期类型赋值前端表单_Spring Boot实践--前端字符串日期自动转换成后台date类型。...

    简单介绍 在前后台开发的时候:日期格式会转来转去,很麻烦.大致总结如下: 1:后端返回对象:可以使用spring提供的:HttpMessageConverter来自动转换,有很多实现. 比如:Abst ...

  8. jQuery form表单的serialize()参数和其他参数 如何一起传给后端

    在前端给后端传递参数时,有时候form表单,我们为了方便,直接可以通过 var formData=$("#formid").serialize();来统一传给后端,这样可以节省很多 ...

  9. Python Day 67 Dango框架图解(总结)、Wsgiref和uwsgi、前后端传输数据的编码格式、From表单和Ajax方式在前端往后端发送文件、补充一下页面清缓存...

    ##Django框架图解 ##前后端传输数据的编码格式 #前后端传输数据的编码格式1.urlencoded 2.formdata 3.application/json ##From表单和Ajax方式在 ...

最新文章

  1. python 添加数据库表_通过时间表(Python库)简化复杂的计划
  2. php微信商户下载对账单,浅析微信支付:下载对账单和资金账单
  3. Project2010简易操作指南[转]
  4. 包管理和环境管理软件Anaconda
  5. 在矩池云中保存Conda环境
  6. KVM详解(二)——KVM安装部署
  7. Cadence安装教程(亲测记录)
  8. 【SpringBoot 】 组件管理 ,java工程师面试突击中华石杉
  9. DID 去中心化数字身份
  10. uc浏览器怎么播放html5,uc视频社区 手机UC浏览器不能看视频了怎么办?
  11. html页面的dtd是什么意思,html dtd文件解释
  12. 豌豆荚PC端版本WanDouJia_2.80.1.7144_homepage.exe
  13. 前端的组件化和模块化
  14. 【手写 Vue2.x 源码】第十八篇 - 根据 render 函数,生成 vnode
  15. idea debug下断点没有对勾的问题
  16. Python新建、写入和修改txt(文本文档)
  17. 【转】什么是加密经济学
  18. 平均数,中位数和众数
  19. 查看当前jdk所支持的jvm参数
  20. 蓝牙防丢器原理、实现与Android BLE接口编程

热门文章

  1. nginx的作用及原理(一)
  2. python画八卦图的指令_如何绘制八卦图?CorelDRAW快速绘制太极八卦图形
  3. 什么是模块化,为什么要模块化?
  4. 美国买车维权,是怎样告别“按‘闹’分配”的?
  5. rbf神经网络matlab代码_【新书推荐】【2008.06】机器人控制系统的设计与MATLAB仿真(刘金琨)...
  6. 计算机二进制小数加法,二进制是如何将加减乘除变换为加法实现的
  7. java.sql.Date日期比较
  8. 小陈java学习笔记0805
  9. kaggle数据集下载步骤
  10. 修复typec otg数据线