# Custom Field Types — Build Pattern
Complete reference for building custom field types in Craft CMS 5: class structure, static configuration, value lifecycle, settings, input HTML, validation, search keywords, GraphQL integration, and relation fields. For using built-in field types and field layout elements, see `fields.md`. For registering field types via events, see `events.md`.
## Documentation
- Field types: https://craftcms.com/docs/5.x/extend/field-types.html
- Generator: https://craftcms.com/docs/5.x/extend/generator.html
## Common Pitfalls
- Reaching for the old `getContentColumnType()` instance method — Craft 5 removed it. The static `dbType()` is the sole mechanism for declaring a custom field's column type.
- Forgetting `parent::defineRules()` in field settings validation — drops validation for `handle`, `name`, and other base properties.
- Not calling `parent::afterElementSave()` — base class handles relation storage, delta writes, and propagation. Skipping it silently breaks multi-site and delta saves.
- Returning a query from `normalizeValue()` without implementing `EagerLoadingFieldInterface` — causes N+1 queries when multiple elements are loaded. Relation fields must be eager-loadable.
- Implementing `getContentGqlType()` without `getContentGqlMutationArgumentType()` — makes the field read-only in GraphQL mutations.
- Setting `searchable` on the field trait without implementing `getSearchKeywords()` — indexed keywords will be empty, making the field unsearchable despite the flag.
## Contents
- [Scaffold](#scaffold)
- [Class Hierarchy](#class-hierarchy)
- [Static Configuration Methods](#static-configuration-methods)
- [Value Lifecycle](#value-lifecycle)
- [Settings](#settings)
- [Input HTML](#input-html)
- [Validation](#validation)
- [Search Keywords](#search-keywords)
- [GraphQL Integration](#graphql-integration)
- [Preview and Static HTML](#preview-and-static-html)
- [Element Lifecycle Hooks](#element-lifecycle-hooks)
- [Relation Fields](#relation-fields)
- [Registration](#registration)
- [Key FieldTrait Properties](#key-fieldtrait-properties)
## Scaffold
```bash
ddev craft make field-type
```
Generates a field type class with stubs for: `displayName()`, `defineRules()`, `getSettingsHtml()`, `dbType()`, `normalizeValue()`, `inputHtml()`, `getElementValidationRules()`, `getSearchKeywords()`, `getElementConditionRuleType()`.
## Class Hierarchy
```
craft\base\Field
extends SavableComponent
extends ConfigurableComponent
extends Component (craft)
extends Model (yii)
```
**Optional interfaces** for enhanced behavior:
| Interface | Enables |
|-----------|---------|
| `PreviewableFieldInterface` | `getPreviewHtml()` for element index tables/cards |
| `SortableFieldInterface` | `getSortOption()` for index sorting |
| `InlineEditableFieldInterface` | Inline editing in element indexes |
| `EagerLoadingFieldInterface` | Eager-loading support for query fields |
| `ThumbableFieldInterface` | Thumbnail in element cards |
| `MergeableFieldInterface` | Merge support for drafts |
## Static Configuration Methods
| Method | Return | Default | Purpose |
|--------|--------|---------|---------|
| `displayName()` | `string` | Class name | Name shown in the field type picker |
| `icon()` | `string` | `'i-cursor'` | SVG icon name |
| `phpType()` | `string` | `'mixed'` | PHP type hint for IDE autocompletion on `entry.myField` |
| `dbType()` | `string\|array\|null` | `Schema::TYPE_TEXT` | DB column type. `null` = self-managed storage |
| `isMultiInstance()` | `bool` | `dbType() !== null` | Whether multiple instances can exist in one field layout |
| `supportedTranslationMethods()` | `array` | All 5 when `dbType()` is non-null | Which translation methods the field supports |
| `queryCondition()` | `array\|ExpressionInterface\|false\|null` | Parent impl | Custom query filtering for `entry.myField(value)` |
| `isRequirable()` | `bool` | `true` | Whether the field can be marked required |
### dbType() options
```php
// Simple column
public static function dbType(): string
{
return Schema::TYPE_TEXT;
}
// Specific size
public static function dbType(): string
{
return Schema::TYPE_STRING . '(255)';
}
// Multi-column
public static function dbType(): array
{
return [
'date' => Schema::TYPE_DATETIME,
'timezone' => Schema::TYPE_STRING,
];
}
// Self-managed storage (relation fields, external APIs)
public static function dbType(): null
{
return null;
}
```
Common types: `TYPE_TEXT`, `TYPE_STRING`, `TYPE_INTEGER`, `TYPE_BOOLEAN`, `TYPE_FLOAT`, `TYPE_JSON`, `TYPE_DATETIME`.
## Value Lifecycle
Values flow through these methods in order:
```
POST data / DB row
│
▼
normalizeValueFromRequest() ← POST data path
│ (delegates to normalizeValue() by default)
▼
normalizeValue() ← DB data path
│ (transforms raw value to working PHP object)
▼
Working PHP value ← available as entry.myField in Twig
│
▼
serializeValue() ← converts back for DB storage
│ (handles Serializable, Arrayable, DateTime)
▼
serializeValueForDb() ← final DB-bound value
```
### normalizeValue()
```php
public function normalizeValue(mixed $value, ?ElementInterface $element = null): mixed
{
if ($value instanceof MyValueObject) {
return $value;
}
if (is_string($value)) {
return new MyValueObject(Json::decodeIfJson($value));
}
if (is_array($value)) {
return new MyValueObject($value);
}
return new MyValueObject();
}
```
### normalizeValueFromRequest()
Override separately when POST data needs different handling than DB data:
```php
public function normalizeValueFromRequest(mixed $value, ?ElementInterface $element = null): mixed
{
// POST data comes as flat array from form inputs
if (is_array($value) && isset($value['date'], $value['timezone'])) {
return new MyValueObject(
DateTimeHelper::toDateTime($value['date']),
$value['timezone']
);
}
return parent::normalizeValueFromRequest($value, $element);
}
```
### serializeValue()
```php
public function serializeValue(mixed $value, ?ElementInterface $element = null): mixed
{
if ($value instanceof MyValueObject) {
return $value->toArray();
}
return parent::serializeValue($value, $element);
}
```
## Settings
### Declaring settings
Public properties on the field class are settings:
```php
public int $maxLength = 255;
public bool $multiline = false;
public string $placeholder = '';
```
**What `settingsAttributes()` actually includes** (applies to every `ConfigurableComponent` — fields, widgets, filesystems): every public non-static property **whose declaring class is not abstract** (`craft\base\ConfigurableComponent::settingsAttributes()`, cms 5.10.12). Consequences that get reasoned about wrongly:
- Properties declared on a concrete subclass are included automatically — **no override needed**. Don't add an explicit `settingsAttributes()` list "to register" them.
- An **abstract** base class's own shared properties are excluded, which is the only legitimate reason for an explicit override: the abstract base lists them, merged with `parent::settingsAttributes()`.
- A concrete subclass that *redeclares* an inherited property (to change its default) flips the declaring class to concrete, so the name appears **twice** in the merged array. Harmless at runtime, but if you're deduping, wrap in `array_unique()` — removing the redeclaration instead would silently change the default.
### Validating settings
```php
protected function defineRules(): array
{
$rules = parent::defineRules(); // Always call parent
$rules[] = [['maxLength'], 'integer', 'min' => 1, 'max' => 65535];
$rules[] = [['placeholder'], 'string', 'max' => 255];
return $rules;
}
```
### Settings UI
```php
public function getSettingsHtml(): ?string
{
return Craft::$app->getView()->renderTemplate(
'my-plugin/fields/_settings',
['field' => $this]
);
}
```
## Input HTML
```php
protected function inputHtml(mixed $value, ?ElementInterface $element, bool $inline): string
{
// $value is already normalized
// $element is null for default-value scenarios
// $inline is true for inline editing in element indexes
return Craft::$app->getView()->renderTemplate(
'my-plugin/fields/_input',
[
'field' => $this,
'value' => $value,
'element' => $element,
]
);
}
```
Set `useFieldset()` to return `true` to wrap input in a `