分组字段

Group Field(分组字段)允许将多个字段嵌套在一个公共属性名下。它还会在Admin Panel中将字段进行视觉上的分组。

展示Payload Admin Panel中的Group字段
Admin Panel中Group字段的截图

要添加Group Field,只需在你的字段配置中将type设置为group

import type { Field } from 'payload'

export const MyGroupField: Field = {
  // ...
  // highlight-start
  type: 'group',
  fields: [
    // ...
  ],
  // highlight-end
}

配置选项

选项描述
name作为属性名用于数据库存储和检索。了解更多
fields *嵌套在此 Group 中的字段类型数组。
label用作 Admin Panel 中的标题和生成的 GraphQL 类型名称。如果未定义,默认使用字段名。
validate提供自定义验证函数,该函数将在 Admin Panel 和后台执行。了解更多
saveToJWT如果该字段是顶级字段且嵌套在支持身份验证的配置中,则将其数据包含在用户 JWT 中。
hooks提供字段钩子来控制该字段的逻辑。更多详情
access提供字段访问控制,指定用户可以查看和操作该字段数据的权限。更多详情
hidden完全限制该字段在所有 API 中的可见性。仍会保存到数据库,但不会出现在任何 API 或 Admin Panel 中。
defaultValue提供用于该字段默认值的数据对象。了解更多
localized启用该字段的本地化功能。需要在基础配置中启用本地化。如果启用,将保留该 Group 内所有数据的单独本地化副本,因此无需将每个嵌套字段指定为 localized
admin管理员特定配置。更多详情
custom用于添加自定义数据的扩展点(例如插件使用)
interfaceName创建顶层的可重用 Typescript 接口GraphQL 类型
typescriptSchema通过提供 JSON schema 来覆盖字段类型生成
virtual设置为 true 可禁用数据库中的字段。参见虚拟字段

* 星号表示该属性为必填项。

管理选项

要自定义 Group Field 在管理面板中的外观和行为,可以使用 admin 选项:

import type { Field } from 'payload'

export const MyGroupField: Field = {
  // ...
  admin: {
    // highlight-line
    // ...
  },
}

Group Field 继承了基础字段管理配置中的所有默认选项,并额外支持以下选项:

Option描述
hideGutter将此属性设置为 true 可隐藏该字段在管理面板中的 gutter。字段 gutter 会渲染为垂直线和间距,但如果该字段嵌套在 Group、Block 或 Array 中,你可能希望隐藏 gutter。

示例

collections/ExampleCollection.ts

import type { CollectionConfig } from 'payload'

export const ExampleCollection: CollectionConfig = {
  slug: 'example-collection',
  fields: [
    {
      name: 'pageMeta',
      type: 'group', // 必填
      interfaceName: 'Meta', // 可选
      fields: [
        // 必填
        {
          name: 'title',
          type: 'text',
          required: true,
          minLength: 20,
          maxLength: 100,
        },
        {
          name: 'description',
          type: 'textarea',
          required: true,
          minLength: 40,
          maxLength: 160,
        },
      ],
    },
  ],
}

展示性分组字段

你也可以使用 Group 字段仅对字段进行视觉上的分组,而不会影响数据结构。不定义 label 时,将只渲染分组后的字段。

import type { CollectionConfig } from 'payload'

export const ExampleCollection: CollectionConfig = {
  slug: 'example-collection',
  fields: [
    {
      label: '页面元信息',
      type: 'group', // 必需
      fields: [
        {
          name: 'title',
          type: 'text',
          required: true,
          minLength: 20,
          maxLength: 100,
        },
        {
          name: 'description',
          type: 'textarea',
          required: true,
          minLength: 40,
          maxLength: 160,
        },
      ],
    },
  ],
}