Custom Field Type and Admin Widget
Build a structured money FieldTypeInterface with a custom Admin UI FieldFormWidgetInterface, Twig partial via AdminTemplateNamespaceProviderInterface, module registration, and an in-process PHPUnit test.
Custom Field Type and Admin Widget
This recipe builds a complete money field type ({ amount_cents: int, currency: string }) that works seamlessly across field_storage.create, compiled bundle JSON Schemas, JSON:API, MCP, and the /admin/content HTML forms with a dedicated Twig widget partial.
What You Will Build
MoneyFieldTypeimplementingFieldTypeInterface(phrame.field_type)MoneyFieldWidgetimplementingFieldFormWidgetInterface(phrame.admin_field_widget)CommerceTemplateNamespaceProviderimplementingAdminTemplateNamespaceProviderInterface(phrame.admin_template_namespace)@acme_commerce/widgets/money.html.twigTwig widget partialCommerceModulewiring all three services withModuleInterface- An in-process PHPUnit test verifying schema compilation, entity persistence, and Admin form coercion + rendering
Step 1: Implement FieldTypeInterface
Create src/Field/MoneyFieldType.php. A custom field type defines its machine name, compiled JSON Schema fragment, domain validation, and storage normalization:
<?php
declare(strict_types=1);
namespace Acme\Commerce\Field;
use PhrameCms\Core\Schema\ValidationError;
use PhrameCms\Core\Schema\ValidationResult;
use PhrameCms\Entity\Contract\FieldTypeInterface;
use PhrameCms\Entity\Schema\FieldInstanceDefinition;
use PhrameCms\Entity\Schema\FieldStorageDefinition;
final readonly class MoneyFieldType implements FieldTypeInterface
{
public const string TYPE = 'money';
public function type(): string
{
return self::TYPE;
}
/** @return array<string, mixed> */
public function jsonSchema(FieldStorageDefinition $storage, FieldInstanceDefinition $instance): array
{
$schema = [
'type' => 'object',
'required' => ['amount_cents', 'currency'],
'properties' => [
'amount_cents' => ['type' => 'integer', 'minimum' => 0],
'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$'],
],
'additionalProperties' => false,
];
$allowedCurrencies = $instance->constraints['currencies'] ?? $storage->settings['currencies'] ?? null;
if (is_array($allowedCurrencies) && $allowedCurrencies !== []) {
$schema['properties']['currency']['enum'] = array_values($allowedCurrencies);
}
return $schema;
}
public function validate(
mixed $value,
FieldStorageDefinition $storage,
FieldInstanceDefinition $instance,
): ValidationResult {
if (!is_array($value)) {
return ValidationResult::invalid([
new ValidationError('', 'Money value must be an object with amount_cents and currency.', 'type'),
]);
}
$errors = [];
if (!is_int($value['amount_cents'] ?? null) || $value['amount_cents'] < 0) {
$errors[] = new ValidationError('/amount_cents', 'amount_cents must be a non-negative integer.', 'minimum');
}
$currency = $value['currency'] ?? null;
if (!is_string($currency) || preg_match('/\A[A-Z]{3}\z/', $currency) !== 1) {
$errors[] = new ValidationError('/currency', 'currency must be a 3-letter ISO-4217 code (e.g. USD).', 'pattern');
}
return $errors === [] ? ValidationResult::valid() : ValidationResult::invalid($errors);
}
public function normalize(mixed $value, FieldStorageDefinition $storage): mixed
{
if (!is_array($value)) {
return $value;
}
return [
'amount_cents' => (int) ($value['amount_cents'] ?? 0),
'currency' => strtoupper(trim((string) ($value['currency'] ?? ''))),
];
}
public function denormalize(mixed $value, FieldStorageDefinition $storage): mixed
{
return $value;
}
}Step 2: Implement FieldFormWidgetInterface
Create src/Admin/MoneyFieldWidget.php. SchemaFormMapper and FormViewBuilder resolve services tagged FieldFormWidgetInterface::SERVICE_TAG (phrame.admin_field_widget) in descending priority order; the first widget whose supports($fieldType) returns true handles HTML rendering, form formatting, and POST coercion:
<?php
declare(strict_types=1);
namespace Acme\Commerce\Admin;
use Acme\Commerce\Field\MoneyFieldType;
use PhrameCms\Admin\Contract\FieldFormWidgetInterface;
use PhrameCms\Admin\Form\FieldCoercionResult;
use PhrameCms\Admin\Form\FormFieldDescriptor;
use PhrameCms\Core\Schema\ValidationError;
use PhrameCms\Entity\Schema\FieldInstanceDefinition;
use PhrameCms\Entity\Schema\FieldStorageDefinition;
final readonly class MoneyFieldWidget implements FieldFormWidgetInterface
{
public function supports(string $fieldType): bool
{
return $fieldType === MoneyFieldType::TYPE;
}
public function inputType(FieldStorageDefinition $storage, FieldInstanceDefinition $instance): string
{
// Must be one of FormFieldDescriptor::INPUT_TYPES
return 'text';
}
public function template(): ?string
{
return '@acme_commerce/widgets/money.html.twig';
}
public function coerce(mixed $rawValue, FormFieldDescriptor $descriptor, string $path): FieldCoercionResult
{
if (!is_string($rawValue) || trim($rawValue) === '') {
return FieldCoercionResult::empty();
}
$trimmed = trim($rawValue);
if (preg_match('/\A(\d+)(?:\.(\d{2}))?\s+([A-Za-z]{3})\z/', $trimmed, $matches) !== 1) {
return FieldCoercionResult::errors([
new ValidationError(
path: $path,
message: 'Enter a price as "19.99 USD" or "25 EUR".',
keyword: 'format',
),
]);
}
$whole = (int) $matches[1];
$cents = $matches[2] !== '' ? (int) $matches[2] : 0;
return FieldCoercionResult::value([
'amount_cents' => ($whole * 100) + $cents,
'currency' => strtoupper($matches[3]),
]);
}
public function formatForForm(mixed $value, FormFieldDescriptor $descriptor): string
{
if (
is_array($value)
&& is_int($value['amount_cents'] ?? null)
&& is_string($value['currency'] ?? null)
) {
return sprintf(
'%d.%02d %s',
intdiv($value['amount_cents'], 100),
$value['amount_cents'] % 100,
$value['currency'],
);
}
return is_string($value) ? $value : '';
}
}Step 3: Add the Twig Template Namespace & Widget Partial
Register a module-scoped Twig namespace (matching /\A[a-z][a-z0-9_]*\z/, excluding reserved admin_base) in src/Admin/CommerceTemplateNamespaceProvider.php:
<?php
declare(strict_types=1);
namespace Acme\Commerce\Admin;
use PhrameCms\Admin\Contract\AdminTemplateNamespaceProviderInterface;
final readonly class CommerceTemplateNamespaceProvider implements AdminTemplateNamespaceProviderInterface
{
/** @return array<string, string> */
public function namespaces(): array
{
return [
'acme_commerce' => dirname(__DIR__, 2) . '/templates',
];
}
}Create templates/widgets/money.html.twig. When partials/form_fields.html.twig renders a custom widget, it executes {% include field.widget_template with { field: field } only %} and renders field.description and field.errors automatically right after your partial:
<label class="form-label" for="field_{{ field.name }}">
{{ field.label }}
{% if field.required %}<span class="form-required" aria-hidden="true">*</span>{% endif %}
</label>
<input
class="form-input"
id="field_{{ field.name }}"
type="text"
name="fields[{{ field.name }}]"
value="{{ field.value }}"
placeholder="19.99 USD"
autocomplete="off"
{% if field.required %}required{% endif %}
>Override support: Site owners can override this partial without editing
vendor/by placing a file attemplates/admin/modules/acme_commerce/widgets/money.html.twig.
Step 4: Wire Everything in ModuleInterface
Create src/CommerceModule.php and register it in config/modules.php (or via Composer extra.phramecms.modules):
<?php
declare(strict_types=1);
namespace Acme\Commerce;
use Acme\Commerce\Admin\CommerceTemplateNamespaceProvider;
use Acme\Commerce\Admin\MoneyFieldWidget;
use Acme\Commerce\Field\MoneyFieldType;
use PhrameCms\Admin\AdminModule;
use PhrameCms\Admin\Contract\AdminTemplateNamespaceProviderInterface;
use PhrameCms\Admin\Contract\FieldFormWidgetInterface;
use PhrameCms\Core\Contract\ContainerBuilderInterface;
use PhrameCms\Core\Contract\ModuleInterface;
use PhrameCms\Entity\Contract\FieldTypeInterface;
use PhrameCms\Entity\EntityModule;
use Psr\Container\ContainerInterface;
final readonly class CommerceModule implements ModuleInterface
{
public const string NAME = 'acme.commerce';
public function name(): string
{
return self::NAME;
}
/** @return list<string> */
public function dependencies(): array
{
return [EntityModule::NAME, AdminModule::NAME];
}
public function register(ContainerBuilderInterface $builder): void
{
$builder->autowire(MoneyFieldType::class, [FieldTypeInterface::SERVICE_TAG]);
$builder->autowire(
CommerceTemplateNamespaceProvider::class,
[AdminTemplateNamespaceProviderInterface::SERVICE_TAG],
);
$builder->autowire(MoneyFieldWidget::class);
$builder->tag(MoneyFieldWidget::class, FieldFormWidgetInterface::SERVICE_TAG, priority: 10);
}
public function boot(ContainerInterface $container): void {}
}Once registered, attach a money field to any bundle via CLI, MCP, or /admin/schema:
./bin/phrame op:run field_storage.create \
--input='{"entity_type":"content","name":"price","type":"money","settings":{"currencies":["USD","EUR"]}}' \
--scopes=schema.modify --json
./bin/phrame op:run field_instance.attach \
--input='{"entity_type":"content","bundle":"product","field_name":"price","label":"Price","required":true}' \
--scopes=schema.modify --jsonStep 5: Test Completely In-Process
Verify schema compilation, entity persistence, form coercion, and Twig rendering with zero external database servers:
<?php
declare(strict_types=1);
namespace Acme\Commerce\Tests;
use Acme\Commerce\CommerceModule;
use PhrameCms\Admin\AdminModule;
use PhrameCms\Admin\Contract\TemplateRendererInterface;
use PhrameCms\Admin\Form\FormViewBuilder;
use PhrameCms\Admin\Form\SchemaFormMapper;
use PhrameCms\Config\ConfigModule;
use PhrameCms\Core\Kernel;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationBus;
use PhrameCms\Core\Operation\OperationRequest;
use PhrameCms\Core\Security\ActorType;
use PhrameCms\Database\DatabaseModule;
use PhrameCms\Database\Schema\SchemaInstallRunner;
use PhrameCms\Entity\Contract\BundleSchemaCompilerInterface;
use PhrameCms\Entity\Contract\EntitySchemaRegistryInterface;
use PhrameCms\Entity\EntityModule;
use PhrameCms\Routing\RoutingModule;
use PhrameCms\User\Security\AuthenticatedActor;
use PhrameCms\User\UserModule;
use PHPUnit\Framework\TestCase;
final class MoneyFieldTest extends TestCase
{
public function testMoneyFieldTypeAndAdminWidgetEndToEnd(): void
{
$kernel = new Kernel([
new DatabaseModule('memory://'),
new ConfigModule(),
new RoutingModule(),
new UserModule(),
new EntityModule(),
new AdminModule(),
new CommerceModule(),
]);
$kernel->boot();
$container = $kernel->container();
$container->getTyped(SchemaInstallRunner::class, SchemaInstallRunner::class)->installAll();
$bus = $container->getTyped(OperationBus::class, OperationBus::class);
$admin = new AuthenticatedActor(id: 'usr_admin', type: ActorType::Human, scopes: ['*']);
$ctx = new ExecutionContext(actor: $admin, correlationId: 'money-test');
$bus->execute(new OperationRequest('entity_type.create', ['id' => 'content', 'label' => 'Content'], $ctx));
$bus->execute(new OperationRequest('bundle.create', ['entity_type' => 'content', 'id' => 'product', 'label' => 'Product'], $ctx));
$bus->execute(new OperationRequest('field_storage.create', ['entity_type' => 'content', 'name' => 'price', 'type' => 'money'], $ctx));
$bus->execute(new OperationRequest('field_instance.attach', [
'entity_type' => 'content',
'bundle' => 'product',
'field_name' => 'price',
'label' => 'Price',
'required' => true,
], $ctx));
// 1. Verify Admin form coercion turns "19.99 usd" into canonical money object
$compiler = $container->getTyped(BundleSchemaCompilerInterface::class, BundleSchemaCompilerInterface::class);
$registry = $container->getTyped(EntitySchemaRegistryInterface::class, EntitySchemaRegistryInterface::class);
$mapper = $container->getTyped(SchemaFormMapper::class, SchemaFormMapper::class);
$descriptors = $mapper->mapFields(
bundleSchema: $compiler->compile('content', 'product'),
instances: $registry->listFieldInstances('content', 'product'),
storages: $registry->listFieldStorages('content'),
);
$coerced = $mapper->coerceSubmission($descriptors, ['price' => '19.99 usd']);
self::assertSame(['price' => ['amount_cents' => 1999, 'currency' => 'USD']], $coerced);
// 2. Persist through OperationBus and verify Twig widget rendering
$created = $bus->execute(new OperationRequest('entity.create', [
'entity_type' => 'content',
'bundle' => 'product',
'fields' => $coerced,
], $ctx));
self::assertSame(1999, $created->data['entity']['fields']['price']['amount_cents']);
$viewBuilder = $container->getTyped(FormViewBuilder::class, FormViewBuilder::class);
$renderer = $container->getTyped(TemplateRendererInterface::class, TemplateRendererInterface::class);
$html = $renderer->render('partials/form_fields.html.twig', [
'fields' => $viewBuilder->buildFieldViews($descriptors, $created->data['entity']['fields']),
]);
self::assertStringContainsString('value="19.99 USD"', $html);
self::assertStringContainsString('name="fields[price]"', $html);
}
}Related Documentation
- Custom Modules Guide — Module lifecycle, hexagonal Twig boundaries, and template override precedence.
- Service Tags Reference — Details on
phrame.field_type,phrame.admin_field_widget, andphrame.admin_template_namespace.