Example 3: Fields and Tool API tools¶
A field on a bundle becomes one resource, field.instance, with three operations: create adds an existing field to another bundle; create_with_storage makes a new field, its storage included; and update changes a field on its bundle. Each operation becomes a Tool API tool. The three read one structure, so their inputs agree.
Today¶
Tool Belt, the contributed module of ready-made Tool API tools, ships one plugin class per action on fields. field_add and field_update each declare label, description, required and settings in their own attribute, and the copies already differ: field_add describes the label as the "human-readable label for the field on this bundle", field_update as the "human-readable label for the field". Nothing makes them agree.
For a field type's settings, field_add reads the config schema, the only description it can reach. The address module states its field settings in five places: its config schema, defaultFieldSettings(), fieldSettingsForm() with the labels and allowed values, and two rules in PHP. The Tool API tool offers what config schema says and nothing the form knows.
The field resource¶
The field resource is declared once, for every field type; in core it would sit in the field module. Identity, storage and access are on the class:
#[Resource('field.instance',
identity: ['entity_type', 'bundle', 'field_name', 'field_type'],
storage: FieldInstanceResourceStorage::class,
access: FieldInstanceAccess::class,
)]
final class FieldInstanceResource implements ResourceInterface {
The three operations are methods on the class. A method's parameters are what the caller names up front: the entity type and the bundle, and for create and update the field too:
#[Operation('create',
label: new TranslatableMarkup('Add an existing field to another bundle'),
description: new TranslatableMarkup('Adds a field whose storage already exists to another bundle of the same entity type, sharing that storage; the storage is changed through field.storage.'),
creates: TRUE,
idempotent: TRUE,
omits: ['storage'],
)]
public static function create(string $entity_type, string $bundle, string $field_name): OperationContext {
return new OperationContext('create', creates: TRUE, known: [
'entity_type' => $entity_type,
'bundle' => $bundle,
'field_name' => $field_name,
]);
}
#[Operation('create_with_storage',
label: new TranslatableMarkup('Create a new field'),
description: new TranslatableMarkup('Creates a field and its storage, and adds it to a bundle of an entity type, under a machine name the caller chooses.'),
creates: TRUE,
idempotent: TRUE,
)]
public static function createWithStorage(string $entity_type, string $bundle): OperationContext {
$context = new OperationContext('create_with_storage', creates: TRUE, known: [
'entity_type' => $entity_type,
'bundle' => $bundle,
]);
$storage = new OperationContext('create', creates: TRUE, known: ['entity_type' => $entity_type]);
return $context->withChild('storage', $storage);
}
#[Operation('update',
label: new TranslatableMarkup('Edit a field'),
description: new TranslatableMarkup('Changes a field; its storage is changed through field.storage. The field is named by its entity type, bundle and machine name, which stay as they are.'),
omits: ['storage'],
)]
public static function update(string $entity_type, string $bundle, string $field_name): OperationContext {
return self::create($entity_type, $bundle, $field_name)->withId('update', creates: FALSE);
}
Each asks the permission Field UI already defines for the entity type, such as administer node fields for a content type. The permission depends on the entity type, so the access class, FieldInstanceAccess, asks it. It reads the entity type from the operation's $entity_type parameter. Each Tool API tool takes entity_type as an input of its own, beside the field's values.
The keys are declared once, in defineInputs(), and every operation reads them. The first four say which field it is, and those the operation already knows are fixed:
public static function defineInputs(BlueprintInterface $inputs): void {
// Which field this is.
$inputs->add('entity_type', Schema::string()->minLength(1)
->title(t('Entity type'))
->description(t('The machine name of the entity type the field is on.'))
->check('drupal:PluginExists', [
'manager' => 'entity_type.manager',
'interface' => FieldableEntityInterface::class,
])
->required());
$inputs->add('bundle', Schema::string()->minLength(1)
->title(t('Bundle'))
->description(t('The bundle the field is on, for example article or page.'))
->required());
$inputs->add('field_type', Schema::string()->minLength(1)
->title(t('Field type'))
->description(t('The field type, which decides what the settings are.'))
->required());
// What a field storage's name may be, which its constructor refuses
// otherwise with an exception rather than a violation.
$inputs->add('field_name', Schema::string()
->title(t('Machine name'))
->description(t('The machine name of the field storage, for example field_tags.'))
->maxLength(FieldStorageConfig::NAME_MAX_LENGTH)
->pattern('^[_a-z]+[_a-z0-9]*$')
->message('pattern', t('The machine name must start with a lowercase letter or underscore, and contain only lowercase letters, numbers and underscores.'))
->required());
// The field itself.
$inputs->add('label', Schema::string()->minLength(1)
->title(t('Label'))
->description(t('The human readable label for the field on this bundle.'))
->required());
$inputs->add('description', Schema::string()
->title(t('Help text'))
->description(t('Help text to display for the field.')));
$inputs->add('required', Schema::bool()
->title(t('Required field'))
->description(t('Whether the field is required.'))
->default(FALSE));
// Its parts.
$inputs->add('storage', Schema::of('field.storage')
->title(t('Field storage'))
->description(t('What every bundle using this field shares.')));
$inputs->add('settings', Schema::object()
->title(t('Field settings'))
->description(t('Settings for this field on this bundle, described by the field type itself.'))
->annotation('x-surface-variants', ['by' => 'field_type', 'from' => FieldSettingsSchemaVariants::class]));
}
settings depends on field_type. A field type that declares its settings structure uses it. Every other field type has its settings read from its config schema, field.field_settings.<field type>, so the Tool API tools can add any field Field UI can.
The storage, a resource of its own¶
A field's storage is shared by every bundle that uses the field: how many values it holds, whether it is translatable, and its settings. It is a second resource, field.storage, whose update and read name it by entity type and field name. A change made there says that it reaches every bundle.
create_with_storage takes a storage as well, because a new field cannot exist without one. One call writes both, the storage first. Schema::of('field.storage') points at the storage resource, so its keys and checks are declared once.
create and update leave it out with omits: ['storage'], so a call that names one bundle's field cannot change the storage other bundles share. The field's read leaves it out too and keeps the keys that name it, so what a read returns can be sent back to update.
Field UI's edit form changes a field and its storage on one page, and that page stays Field UI's. Through the operations, a storage is changed by field.storage:update, in a call and a Tool API tool of its own.
TBD
Deleting a field is not built. Core deletes a storage with its last field, so the storage resource needs no delete of its own.
The address settings¶
The settings belong to the address field type, AddressItem, where fieldSettingsForm() and defaultFieldSettings() are today. This example plays the address module converting its own class, which becomes its own structure: a group of keys the field holds, with no identity, storage or operations of its own:
#[Structure('field.settings.address', storedAs: AddressStoredAs::class)]
#[UsesStructure]
class AddressItem extends FieldItemBase implements AddressInterface, FieldSurfaceProviderInterface, StructureInterface {
use SurfaceFieldTypeTrait;
// The columns, the properties and the accessors are left out.
/**
* {@inheritdoc}
*/
public static function defineInputs(BlueprintInterface $inputs): void {
// The item says what one country code is, and the Country constraint
// is the whole of that.
$inputs->add('available_countries', Schema::list(Schema::string()
->title(t('Country'))
->check('drupal:Country'))
->title(t('Available countries'))
->description(t('Leave empty for all countries.'))
->default([]));
// Locked languages are excluded by default, which is what the address
// module's own settings form does by hand: "not specified" and "not
// applicable" are not languages an address is formatted in.
$inputs->add('langcode_override', Schema::string()
->title(t('Language override'))
->description(t('Ensures entered addresses are always formatted in the same language.'))
->check('drupal:LanguageExists'));
// No override is an empty map, as the address module's own default
// settings say; no key inside starts from a value of its own.
$inputs->add('field_overrides', Schema::object(self::fieldOverrideSchemas())
->title(t('Field overrides'))
->description(t('Override the country-specific address format, forcing properties to always be hidden, optional, or required.'))
->default([]));
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return static::surfaceDefaultFieldSettings(static::class) + [
'langcode_override' => NULL,
// Replaced by field_overrides.
'fields' => [],
];
}
The trait draws Field UI's settings form from those keys, in place of fieldSettingsForm(), and checks it with the declared rules. It also supplies defaultFieldSettings() from the declared defaults. Address writes its own because it stores two more keys: the language override, which declares no default, and the deprecated fields, which its other code still reads. The field resource reads the same structure off the field type: when field_type is address, its settings are this, as Placing a block reads a block plugin's. Neither module names a class of the other.
The address module does not store these settings the way a caller sends them. It stores the list of countries as a map of each code to itself, and wraps each override in an array of its own. storedAs names the class that turns one into the other, toStored() and fromStored(). Whatever holds the structure applies it, so Field UI and the field's operations store the same values.
The proof of concept cannot change the address module, so a subclass of AddressItem carries the structure, swapped in with hook_field_info_alter().
TBD
A field type also has storage settings. #[UsesStructure] names its field settings; how a field type declares the other set is open.
The result: three Tool API tools whose inputs agree¶
The operations become surface:field.instance:create, surface:field.instance:create_with_storage and surface:field.instance:update, with no tool class written. The label's description is the same in all three, from one line of defineInputs(). A change to the structure, such as a reworded description or another field type's settings, reaches all three at once, because none holds a copy.
Before and after: what a tool can read¶
A tool can tell its caller only what it can read itself. The difference here is what there is to read about the address settings, not which tool reads it.
Say the caller, such as an AI agent, wants three things from an address field: only the United States and Canada, a required organization, and a hidden last name. Before it writes anything, all it has is the tool's input schema, read once the field and the bundle are named. The proof of concept's comparison test generates both schemas below.
Before: config schema¶
Config schema is the only description of the settings a tool can read, and it describes how they are stored. tool_belt:field_add builds its settings input from it, so for the overrides it tells the caller this:
"field_overrides": {
"type": [
"array",
"null"
],
"description": "The input definition for Field overrides",
"items": {
"type": [
"object",
"null"
],
"properties": {
"override": {
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "The input definition for Override",
"title": "Override"
}
},
"description": "The input definition for Mapping",
"title": "Mapping"
},
"title": "Field overrides"
},
That is a list of objects, each with one string named override. It does not say which address property an override is for, or what the string may be. Address stores the property as the list's key, and config schema does not describe a list's keys. Following this schema, the closest the caller gets, as settings, is:
{
"available_countries": ["US", "CA"],
"field_overrides": [{"override": "required"}, {"override": "hidden"}]
}
Nothing in it says that the organization is required and the last name hidden. Redesigning the tool would not change that. The property names, the three values and the country list are in the PHP that builds the settings form, so a tool could do better only by writing them out again, for each field type.
After: the declared structure¶
The address field type declares its settings as a structure, and any tool can read it, a hand-written one too. surface:field.instance:create does, so for the overrides it tells the caller this (the first two of twelve properties):
"field_overrides": {
"type": [
"object",
"null"
],
"properties": {
"givenName": {
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"enum": [
"hidden",
"optional",
"required",
null
],
"title": "First name"
},
"additionalName": {
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"enum": [
"hidden",
"optional",
"required",
null
],
"title": "Middle name"
},
create_with_storage is told the field type in the call, so its caller asks surface:field.instance:create_with_storage:schema for the same settings first.
Each address property is named and labeled, with the three values it takes. The caller sends what it wants, as settings:
{
"available_countries": ["US", "CA"],
"field_overrides": {"organization": "required", "familyName": "hidden"}
}
storedAs then writes it the way the address module stores it today.
What changes for the caller¶
| The caller needs to know | From config schema | From the structure |
|---|---|---|
| Which address property an override is for | Not described | Twelve named properties, each with its label |
| What an override may be | Any string | hidden, optional or required |
| Which countries it may list | Any string | The country list, by code |
| Which languages it may choose | Any string | The site's languages |
| What each setting does | Filler text: "The input definition for Override" | A description of the setting |
Whether to use fields |
Offered like any other key. It is deprecated, and when set it overrules field_overrides |
Not offered |
The structure's rules are also what checks the call, and the same structure draws Field UI's form and checks a call over HTTP or Drush. A key the settings do not declare, such as country_code among the overrides, is refused by name, and nothing is created.