Skip to main content

Custom field type

What it does​

Add a field type of your own: it gets a tile in the builder palette, renders on the storefront form, and stores its answer like every core field. A field type is an entry in your module's etc/webforms.xml, three PHP classes, the DI wiring that joins them, and a template. The core types and the field types of the WebForms add-ons are built the same way.

The examples add a Fabric Code field in a module named Northstar_WebFormsFields: a one-line input where a customer enters the code printed on a fabric swatch. Put your own vendor, module and type names in their place.

Before you start​

  • A Magento module of your own with MageMe_WebForms in the <sequence> of its etc/module.xml. See Getting started for developers.
  • File access to the store and a shell where you can run bin/magento.
  • Developer mode while you work. A field type that fails to load breaks more than its own tile, see Limits.

Steps​

Declare the type​

  1. Create etc/webforms.xml in your module. WebForms merges this file from every module, so your type joins the core list:

    <?xml version="1.0"?>
    <webforms xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:module:MageMe_WebForms:etc/webforms.xsd">
    <field_types>
    <type id="fabric_code" order="1000">
    <label>Fabric Code</label>
    <model>Northstar\WebFormsFields\Model\Field\Type\FabricCode</model>
    <category>Text</category>
    <palette>
    <hint>A one-line input for the code printed on a fabric swatch.</hint>
    </palette>
    </type>
    </field_types>
    </webforms>

    The id is the type code stored with every field of this type. It must be unique across all modules. label, model, id and order are required; the other elements are listed in The type entry.

Write the three classes​

  1. Create the model. It extends MageMe\WebForms\Model\Field\AbstractField, which already validates, stores and prints a plain value. Override only what your type does differently:

    <?php
    declare(strict_types=1);

    namespace Northstar\WebFormsFields\Model\Field\Type;

    use MageMe\WebForms\Model\Field\AbstractField;

    class FabricCode extends AbstractField
    {
    public function getValueShape(): ?string
    {
    return self::VALUE_SHAPE_SINGLE;
    }
    }

    getValueShape() tells the submit and API paths whether a list is a valid answer. A type from another module answers null until it overrides the method. See What a type can override.

  2. Create the storefront block. It extends MageMe\WebForms\Block\Form\Element\Field\AbstractField and names its template:

    <?php
    declare(strict_types=1);

    namespace Northstar\WebFormsFields\Block\Form\Element\Field\Type;

    use MageMe\WebForms\Block\Form\Element\Field\AbstractField;

    class FabricCode extends AbstractField
    {
    protected $_template = self::TEMPLATE_PATH . 'fabric_code.phtml';
    }

    TEMPLATE_PATH is form/element/field/type/. The path has no module prefix, so Magento looks for the file in the block's own module: view/frontend/templates/form/element/field/type/fabric_code.phtml of Northstar_WebFormsFields. A theme overrides it under Northstar_WebFormsFields/templates/, not under MageMe_WebForms/templates/.

  3. Create the admin class. It extends MageMe\WebForms\Ui\Field\AbstractField, which builds the builder inspector. The base class also builds the field's column in the submissions grid and its row on the submission edit page, but they show only when the class declares the two interfaces below. See Admin display and export:

    <?php
    declare(strict_types=1);

    namespace Northstar\WebFormsFields\Ui\Field\Type;

    use MageMe\WebForms\Api\Ui\FieldResultFormInterface;
    use MageMe\WebForms\Api\Ui\FieldResultListingColumnInterface;
    use MageMe\WebForms\Ui\Field\AbstractField;

    class FabricCode extends AbstractField implements FieldResultFormInterface, FieldResultListingColumnInterface
    {
    }

Wire the classes together​

  1. In your module's global etc/di.xml, pass the admin class and the block to the model. The core declares each of its types the same way:

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Northstar\WebFormsFields\Model\Field\Type\FabricCode">
    <arguments>
    <argument name="fieldUi" xsi:type="object">Northstar\WebFormsFields\Ui\Field\Type\FabricCode</argument>
    <argument name="fieldBlock" xsi:type="object">Northstar\WebFormsFields\Block\Form\Element\Field\Type\FabricCode</argument>
    </arguments>
    </type>
    </config>

Write the template​

  1. Create view/frontend/templates/form/element/field/type/fabric_code.phtml. Start from a core template with the same kind of input; this one is cut down from the core text.phtml:

    <?php
    /**
    * @var \Northstar\WebFormsFields\Block\Form\Element\Field\Type\FabricCode $block
    * @var \Magento\Framework\Escaper $escaper
    */
    $validationRules = $block->getValidationRules();
    ?>
    <input <?= /* @noEscape */ $block->wfPart('field-input') ?>
    id="<?= $escaper->escapeHtmlAttr($block->getFieldId()) ?>"
    name="<?= $escaper->escapeHtmlAttr($block->getFieldName()) ?>"
    type="text"
    class="<?= $escaper->escapeHtmlAttr($block->getFieldClass()) ?>"
    value="<?= $escaper->escapeHtmlAttr((string)$block->getFieldValue()) ?>"
    <?php if ($validationRules): ?>
    data-validate="{<?= $escaper->escapeHtmlAttr(implode(', ', $validationRules)) ?>}"
    <?php endif; ?>
    <?php if ($block->getIsLabelHidden()): ?>
    aria-label="<?= $escaper->escapeHtmlAttr($block->getFieldLabel()) ?>"
    <?php else: ?>
    aria-labelledby="label_<?= $escaper->escapeHtmlAttr($block->getFieldId()) ?>"
    <?php endif; ?>
    <?php if ($block->getIsRequired()): ?>aria-required="true"<?php endif; ?>
    />

    This cut-down copy leaves out what the core template also prints: the custom validation messages (getValidationDescriptions()), the inline style, placeholder, text direction, autocomplete, the field's custom attributes, the input mask and the customer data prefill. Copy those lines from text.phtml when your type should honour the matching settings.

    Keep the name from getFieldName(): the form posts every control of its <form> element, and the server reads the answer under that name. Keep wfPart('field-input') so the input carries the Styling contract attribute.

Install the module​

  1. Enable the module and update the store:

    bin/magento module:enable Northstar_WebFormsFields
    bin/magento setup:upgrade
    bin/magento cache:clean

    In production mode also run bin/magento setup:di:compile and deploy static content.

What you should see​

  • The builder palette has a Fabric Code tile. Without a palette/label the tile shows the type's label.
  • A field of the new type renders from your template on the storefront form, and its answer is stored and shown like a text answer.
  • Submissions of a form with the field show a Fabric Code column in the form's submission grid and a row on the submission edit page.
  • The API lists the type code next to the core types: GET /V1/webforms/capabilities returns fabric_code in field_types. See REST: Capabilities.

The type entry​

Element Required What it does
id attribute Yes The type code, unique across all modules (xs:ID in the schema).
order attribute Yes Sort order among the types of the same palette group.
label Yes The type's name in the builder, the API and the submissions grid.
model Yes The model class. It must implement MageMe\WebForms\Api\Data\FieldInterface; extending AbstractField does that.
category No Picks the palette group, see below.
value No The type attribute that holds the field's default value, as in the core types (text for Text, init_stars for Rating).
logic No true lets the field trigger conditional logic. The Zendesk add-on sets it on its drop-downs.
attributes No The type's own settings, one <attribute name="…"/> each. Add internal="true" to an attribute the module keeps for itself: it is left out of the API, exports and imports, and isn't copied with the form.
assets No Storefront assets the type needs, by reference to an <asset> declared in an <assets> stack.
palette No The tile: a short label, an icon (inner SVG markup in CDATA, on a 256 grid unless the grid attribute says otherwise) and a one-sentence hint.

The palette group comes from the category. Text goes to Text Input; Select and Rating to Options; Date to Date & time; File and Signature to Files & media; Newsletter to Store data; Map and Grid to Advanced. Any other category goes to Advanced, unless your module declares a group for it:

<palette_groups>
<group category="Northstar">
<icon grid="24"><![CDATA[<path fill="currentColor" d="M4 4h16v16H4z"/>]]></icon>
</group>
</palette_groups>

palette_groups sits next to field_types in the same file. The Zendesk add-on uses it for its three drop-downs: category Zendesk and a group with the Zendesk mark.

What a type can override​

Copy the signatures exactly: the parameters that are optional in the parent class stay optional.

Method Class Default Override when
getValueShape() model null for a type of another module Always. VALUE_SHAPE_SINGLE refuses a list on every path, VALUE_SHAPE_LIST accepts one. With null the submit paths hand a list to your validation and the API update refuses it.
getValueForIntegration($value, ?int $resultId = null): string|array model The stored string, or a list of strings The stored value isn't what a CRM or helpdesk can use: codes, JSON, file names.
getValueForResultHtml($value, array $options = []) model The stored text, escaped, with line breaks The answer needs its own markup. The admin submission view and grid and the email notifications print it.
getResultText($value, ?int $resultId = null, array $options = []): string (protected) model The stored value as text The answer reads differently from what is stored: a formatted date, a contact's name, a country's name. It is plain text, nothing escaped, one answer per line. The template variable and the export both follow it, so this one method is usually all a type overrides.
getValueForResultTemplate($value, ?int $resultId = null, array $options = []) model getResultText(), escaped, with line breaks turned into <br> The type builds its own markup around the answer, such as a link or a table. It must return safe HTML: {{var result.<code>.value|raw}} in an email or a printed copy prints it unchanged. Escape everything that came from the submission.
getValueForExport($value, ?int $resultId = null) model getResultText() Rarely: an export takes plain text, without markup or HTML entities.
getValidation(): array model The rules from the field's validation settings The input needs its own client-side rule. The Zendesk drop-downs swap required-entry for validate-select.
getUiMeta(string $prefix = ''): array admin class The common settings The type has settings of its own. Return them as UI component metadata, as the core Rating type does for Default Rating and Number of Stars, and list each one under attributes.
isImportPostProcess(): bool and importPostProcess(array $logicMatrix): FieldInterface model Runs only for a field with Required Unless This Field Is Filled set, and remaps that field id A type attribute of yours holds another field's id. See Limits.
getResultListingColumnConfig(int $sortOrder): array admin class The default grid column The grid column needs its own filter or body template. The interface is already declared in step 4.
getResultAdminFormConfig(?ResultInterface $result = null): array admin class The default row on the submission edit page The row needs its own input. The interface is already declared in step 4. To change the exported value, see Admin display and export (ExportValueConverterInterface).

For a working example, read the field types of the Zendesk add-on: ZendeskPriority extends a shared AbstractZendeskSelect model that declares a single value, maps stored codes to labels, and swaps the required rule. Its admin class sets a select filter on the grid column, and its template is a plain <select>.

Print the markup of an answer from a template, not from a PHP string. The model inherits the protected $valueRenderer (MageMe\WebForms\Model\Field\ValueRenderer) from AbstractField; call $this->valueRenderer->render('Northstar_WebFormsFields::field/value/fabric-code.phtml', ['code_html' => $escaped]). The variables are the template block's data, and a variable whose name ends in _html is printed as it is, so put only escaped text into it. The core types' own templates are under view/base/templates/field/value of MageMe_WebForms. A model that declares a property named $valueRenderer of its own clashes with the inherited one.

Admin display and export​

A field of your type shows on the admin pages of a submission only when its admin class says how. The interfaces below tell WebForms how. Short names are relative to MageMe\WebForms\.

Interface Implemented by Without it
Api\Ui\FieldUiInterface The field's admin class, through the base class Ui\Field\AbstractField. It is the type of the fieldUi argument of the field model. —
Api\Utility\Field\FieldBlockInterface The field's storefront block, through Block\Form\Element\Field\AbstractField. It is the type of the fieldBlock argument. —
Api\Ui\FieldResultFormInterface::getResultAdminFormConfig(?ResultInterface $result = null): array The field's admin class The field isn't shown on the submission edit page.
Api\Ui\FieldResultListingColumnInterface::getResultListingColumnConfig(int $sortOrder): array The field's admin class The field has no column in the form's submission grid.
Api\Utility\ExportValueConverterInterface::convertExportValue($data, ?int $resultId) The grid column class of the field, a subclass of Ui\Component\Result\Listing\Column\Field The export writes the stored value as it is.
Api\Utility\Field\UploadFieldInterface (no methods) The field model of a type that stores uploaded files, as the core File field does The API lets a client update the answer like any other. With the marker, it refuses and asks for an upload instead, and the whole update is refused, the other fields included.

The base class Ui\Field\AbstractField already has both methods. Declaring the two interfaces, as in step 4, is enough to show the field with the default settings.

Override a method only to change those settings. Start from the base class's getDefaultUIResultColumnConfig() and getDefaultResultAdminFormConfig() and change only what your type needs. The Mailchimp add-on's group field does this (excerpt):

class MailchimpGroupSelect extends AbstractField implements FieldResultListingColumnInterface, FieldResultFormInterface
{
public function getResultListingColumnConfig(int $sortOrder): array
{
$config = $this->getDefaultUIResultColumnConfig($sortOrder);
$config['filter'] = Filter::SELECT;
$config['options'] = $this->getField()->toOptionArray();
$config['class'] = MailchimpGroupColumn::class;
$config['bodyTmpl'] = BodyTmpl::HTML;
return $config;
}

public function getResultAdminFormConfig(?ResultInterface $result = null): array
{
$isMultiselect = $this->getField()->getIsMultiselect();
$config = $this->getDefaultResultAdminFormConfig();
$config['type'] = $isMultiselect ? 'multiselect' : 'select';
$options = $this->withStoredAnswer($this->getField()->getOptionsForResult($result), $result, false);
$config['values'] = $isMultiselect ? $options : $this->withNoAnswer($options);
return $this->relaxRequiredWhenUnanswered($config, $result);
}
}

The group field's grid column converts the export value (excerpt):

class MailchimpGroup extends Field implements ExportValueConverterInterface
{
public function convertExportValue($data, ?int $resultId)
{
$field = $this->getData('field');
return $field->getValueForExport($data);
}
}

Cache-safe field types​

A form is shared between visitors in the page cache and in fragments only when every field on it is of a type known to be cache-safe. A field type of your own that isn't listed makes every form that uses it uncacheable.

List the type in the global etc/di.xml. Name the item after the type id and give it the type id as its value. An item whose name and value differ is ignored without a message. The Zendesk add-on lists its three field types:

<type name="MageMe\WebForms\Model\Form\Cacheability">
<arguments>
<argument name="cacheSafeFieldTypes" xsi:type="array">
<item name="zendesk_group_select" xsi:type="string">zendesk_group_select</item>
<item name="zendesk_priority_select" xsi:type="string">zendesk_priority_select</item>
<item name="zendesk_type_select" xsi:type="string">zendesk_type_select</item>
</argument>
</arguments>
</type>

A type whose markup depends on its stored content can still opt out per field: override isCacheSafe() of its field model.

A model with dependencies of its own​

A field model that extends Model\Field\AbstractField takes MageMe\WebForms\Model\Field\Context and passes it to the parent unchanged, with the field's admin class and storefront block. Your own dependencies come before the admin class and the block. A dependency the base class gains later goes into the Context, so your constructor stays the same. The Zendesk add-on's Priority field (excerpt):

public function __construct(
Priority $zendeskPriority,
Context $context,
FieldUiInterface $fieldUi,
FieldBlockInterface $fieldBlock
) {
parent::__construct($context, $fieldUi, $fieldBlock);
$this->zendeskPriority = $zendeskPriority;
}
<type name="MageMe\WebFormsZendesk\Model\Field\Type\ZendeskPriority">
<arguments>
<argument name="fieldUi" xsi:type="object">MageMe\WebFormsZendesk\Ui\Field\Type\ZendeskPriority</argument>
<argument name="fieldBlock" xsi:type="object">MageMe\WebFormsZendesk\Block\Form\Element\Field\Type\ZendeskPriority</argument>
</arguments>
</type>

Limits​

  • A constructor of your own follows the 4.0 signatures. The classes above need none. If your storefront block declares one, it passes on the parent's arguments, which include a required MageMe\WebForms\Model\Contract\PartAttributes before $data. If your model declares one, it takes the parent's three arguments, the field context (MageMe\WebForms\Model\Field\Context), the admin class and the block, and passes them on; new core dependencies arrive through the context.

  • A type that throws breaks every type. The field type catalog creates one field of each registered type and reads its settings without catching errors. A constructor or getUiMeta() that throws takes down the whole catalog: the builder inspector and the API schema stop working for every form.

  • Disabling your module turns its fields into Text fields. A stored field whose type is no longer registered is created with the Text model. The stored answers stay.

  • Field references in your own attributes need your code. When a form is copied, imported, or copied into a builder draft or a version, WebForms calls importPostProcess() on each field whose isImportPostProcess() returns true, with a matrix of field_<old id> → new id. A type attribute of yours that holds another field's id keeps the old id unless your model overrides both methods; the core Region type does this for its country field. The rename and draft-publish paths read only the places listed in MageMe\WebForms\Model\Field\Reference\SiteRegistry and don't see your attribute.

  • Hyvä renders your template as you wrote it. The Hyvä companion replaces the templates of the core types only. Write markup that works without RequireJS and Knockout, or the field will not work on Hyvä. A template that relies on either works on Luma only.

  • No executable <script> in the template. In a popup or a fetched slide-out it never runs, and in developer mode the request fails. Storefront code for a field goes in a field adapter, the mechanism described in Custom CAPTCHA provider.

Troubleshooting​

  • The tile isn't in the palette. Check that etc/webforms.xml matches the schema (the id and order attributes, label and model), that the module is enabled, and clean the cache.
  • The builder shows the field with the wrong settings. The DI block for the model is missing or names the wrong classes. Check etc/di.xml, then run bin/magento setup:di:compile in production mode.
  • The builder or the API schema fails for every form. One field type threw while the catalog was built. Look in var/log/exception.log for the class named in the error.
  • The field renders with no input. The template wasn't found. Check the path below view/frontend/templates/ of your module against TEMPLATE_PATH plus the file name in your block.

What's next​

Applies to WebForms 4Last reviewed December 2, 2026