复选框字段
Checkbox 字段在数据库中保存一个布尔值。


管理面板截图:下方带有文本字段的复选框字段
要添加 Checkbox 字段,请在 Field Config 中将 type
设置为 checkbox
:
import type { Field } from 'payload'
export const MyCheckboxField: Field = {
// ...
type: 'checkbox', // highlight-line
}
配置选项
选项 | 描述 |
---|---|
name * | 作为属性名存储在数据库中并从数据库检索时使用。了解更多 |
label | 在 Admin Panel 中用作字段标签的文本,或为每种语言提供键值的对象。 |
validate | 提供自定义验证函数,该函数将在 Admin Panel 和后台执行。了解更多 |
index | 为此字段构建索引以加快查询速度。如果用户会频繁查询此字段的数据,请将此字段设置为 true 。 |
saveToJWT | 如果此字段是顶级字段且嵌套在支持身份验证的配置中,则将其数据包含在用户 JWT 中。 |
hooks | 提供字段钩子来控制此字段的逻辑。更多详情。 |
access | 提供字段访问控制,指定用户可以对此字段数据执行的操作。更多详情。 |
hidden | 完全限制此字段在所有 API 中的可见性。仍会保存到数据库,但不会出现在任何 API 或 Admin Panel 中。 |
defaultValue | 提供用于此字段默认值的数据,如果字段也是 required ,则默认为 false。了解更多 |
localized | 为此字段启用本地化。需要在基础配置中启用本地化。 |
required | 要求此字段必须有值。 |
admin | 特定于 Admin Panel 的配置。更多详情。 |
custom | 用于添加自定义数据(例如插件)的扩展点 |
typescriptSchema | 通过提供 JSON schema 来覆盖字段类型生成 |
virtual | 提供 true 以在数据库中禁用字段,或提供字符串路径来将字段与关系链接。参见虚拟字段 |
* 星号表示该属性是必填项。
示例
以下是一个 Collection 中 Checkbox Field 的示例:
import type { CollectionConfig } from 'payload'
export const ExampleCollection: CollectionConfig = {
slug: 'example-collection',
fields: [
{
name: 'enableCoolStuff', // 必填
type: 'checkbox', // 必填
label: '点击我查看炫酷效果',
defaultValue: false,
},
],
}
自定义组件
字段组件
服务端组件
import type React from 'react'
import { CheckboxField } from '@payloadcms/ui'
import type { CheckboxFieldServerComponent } from 'payload'
export const CustomCheckboxFieldServer: CheckboxFieldServerComponent = ({
clientField,
path,
schemaPath,
permissions,
}) => {
return (
<CheckboxField
field={clientField}
path={path}
schemaPath={schemaPath}
permissions={permissions}
/>
)
}
客户端组件
'use client'
import React from 'react'
import { CheckboxField } from '@payloadcms/ui'
import type { CheckboxFieldClientComponent } from 'payload'
export const CustomCheckboxFieldClient: CheckboxFieldClientComponent = (
props,
) => {
return <CheckboxField {...props} />
}
标签组件
服务端组件
import React from 'react'
import { FieldLabel } from '@payloadcms/ui'
import type { CheckboxFieldLabelServerComponent } from 'payload'
export const CustomCheckboxFieldLabelServer: CheckboxFieldLabelServerComponent =
({ clientField, path }) => {
return (
<FieldLabel
label={clientField?.label || clientField?.name}
path={path}
required={clientField?.required}
/>
)
}
客户端组件
'use client'
import React from 'react'
import { FieldLabel } from '@payloadcms/ui'
import type { CheckboxFieldLabelClientComponent } from 'payload'
export const CustomCheckboxFieldLabelClient: CheckboxFieldLabelClientComponent =
({ label, path, required }) => {
return (
<FieldLabel
label={field?.label || field?.name}
path={path}
required={field?.required}
/>
)
}