Перейти к содержанию
Skillpedia
API и серверы (бэкенд)8.1k · #12585

webiny-api-cms-custom-field-type

Что он делает

Этот скилл показывает вашему ИИ, как добавить новый вид поля в модели контента Webiny. Он нужен разработчикам, которым требуется поле с особым хранением или правилами валидации.

Когда использовать

  • ✓Когда встроенные типы полей Webiny не покрывают нужного, например особого формата.
  • ✓Когда вы хотите, чтобы собственное поле предлагало свои цепочные методы конструктора в коде моделей.
  • ✓Когда собственному полю нужна своя логика валидации.

Ссылка на скилл

https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/custom-field-type/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/webiny/webiny-js/blob/next/skills/user-skills/api/custom-field-type/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Создай собственный тип поля «цвет» для моделей нашей CMS, который проверяет hex-коды.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл объясняет, как построить класс поля со своим конструктором, добавить валидаторы, создать фабрику и зарегистрировать ее. Он также описывает поддержку TypeScript, чтобы новое поле автодополнялось.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Custom CMS Field Type

TL;DR

A custom field type is a class that extends DataFieldBuilder<"yourType">, paired with a factory class implementing FieldType.Factory. Register the factory with container.register(YourFieldType). Add a module augmentation on "webiny/api/cms/model" so the fields registry method gets TypeScript autocomplete.

When to Use This

Use a custom field type when:

  • You need a field with a storage format or validation logic not covered by the built-in types (text, number, boolean, datetime, file, ref, object, richText, longText, json, dynamicZone)
  • You want to expose a fluent builder API (e.g., fields.slug(), fields.color()) in ModelFactory implementations

Field Type Structure

A custom field type consists of three parts:

  1. Builder interface — extends DataFieldBuilder<"type"> plus FieldTypeValidator.* types
  2. Builder class — implements the interface, calls this.validation() for each validator
  3. Factory class — implements FieldType.Factory, creates builder instances

As a standalone extension (not part of a larger feature), the directory layout is:

extensions/
└── SlugFieldType/
    ├── SlugFieldType.ts     # builder interface, builder class, factory class
    └── feature.ts           # createFeature — registers the factory into the DI container

feature.ts:

// extensions/SlugFieldType/feature.ts
import { createFeature } from "webiny/api";
import { SlugFieldType } from "./SlugFieldType.js";

export const SlugFieldTypeFeature = createFeature({
  name: "SlugFieldType",
  register(container) {
    container.register(SlugFieldType);
  }
});

Register in the API entry point:

// api/Extension.ts
import { createFeature } from "webiny/api";
import { SlugFieldTypeFeature } from "~/extensions/SlugFieldType/feature.js";

export const Extension = createFeature({
  name: "MyExtension",
  register(container) {
    SlugFieldTypeFeature.register(container);
  }
});

Complete Example

// extensions/SlugFieldType/SlugFieldType.ts
import { DataFieldBuilder, FieldType } from "webiny/api/cms/model";
import type { FieldTypeValidator } from "webiny/api/cms/model";

// 1. Builder interface — extends DataFieldBuilder + desired FieldTypeValidator types
export interface ISlugFieldBuilder
  extends
    DataFieldBuilder<"slug">,
    FieldTypeValidator.Required,
    FieldTypeValidator.Pattern,
    FieldTypeValidator.Unique {}

// 2. Module augmentation — adds fields.slug() to the registry
declare module "webiny/api/cms/model" {
  interface IFieldBuilderRegistry {
    slug(): ISlugFieldBuilder;
  }

  interface IFieldRendererRegistry {
    myCustomRenderer: {
      fieldType: "text" | "number";
      settings: undefined;
    };
  }
}

// 3. Builder class — implements each validator method via this.validation()
class SlugFieldBuilder extends DataFieldBuilder<"slug"> implements ISlugFieldBuilder {
  constructor() {
    super("slug");
  }

  required(message?: string): this {
    return this.validation({
      name: "required",
      message: message || "Value is required.",
      settings: {}
    });
  }

  pattern(regex: string, flags = "", message?: string): this {
    return this.validation({
      name: "pattern",
      message: message || "Invalid value.",
      settings: { preset: "custom", regex, flags }
    });
  }

  unique(message?: string): this {
    return this.validation({
      name: "unique",
      message: message || "Value must be unique.",
      settings: {}
    });
  }
}

// 4. Factory class — implements FieldType.Factory
class SlugFieldTypeFactory implements FieldType.Factory {
  readonly type = "slug";

  create(): ISlugFieldBuilder {
    return new SlugFieldBuilder();
  }
}

// 5. Export as a FieldType implementation
export const SlugFieldType = FieldType.createImplementation({
  implementation: SlugFieldTypeFactory,
  dependencies: []
});

Using the Custom Field in a Model

After registration, fields.slug() is available in any ModelFactory implementation:

import { ModelFactory } from "webiny/api/cms/model";

class ProductModelImpl implements ModelFactory.Interface {
  async execute(builder: ModelFactory.Builder) {
    return [
      builder
        .public({ modelId: "product", name: "Product", group: "ungrouped" })
        .fields(fields => ({
          name: fields.text().label("Name").required(),
          slug: fields
            .slug()
            .label("Slug")
      
Частые вопросы

Из каких частей состоит собственный тип поля?

Из интерфейса конструктора, класса конструктора и класса фабрики.

Нужно ли сообщать TypeScript о новом поле?

Да. Скилл описывает расширение модуля, чтобы новый метод автодополнялся.

Какие встроенные типы он упоминает?

Текст, число, логическое значение, дату и время, файл, ссылку, объект, форматированный текст, длинный текст, JSON и динамическую зону.

Подробности

Оригинальное описание автора

How to implement a custom CMS field type that integrates with the model builder's fluent API. Covers extending DataFieldBuilder, composing validator interfaces, creating a FieldTypeFactory, registering via DI, and module augmentation for TypeScript autocomplete on the fields() registry.

repo: webiny/webiny-js

Популярность

Звёзды на GitHub
8.1k
Место в рейтинге
#12585
Лицензия
—
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы