Light API 0.18.0 is a public beta: a minor release such as 0.19.0 may still break. What that means for your module
Light
Developer guideRecipes

Fields on a Light editor

A card with your fields on a Light editor, checked on the server and in the browser.

A module adds fields to a Light editor with a card: the product, category, CMS page, CMS block, discount, new-customer and customer contact editors. The card's values load with the entity, are checked before the save, go onto the entity, and save inside the editor's transaction. JS hooks check and extend the save in the browser.

When to use it

  • Your module stores a property of the entity that the merchant sets while editing it, such as a product's delivery note.
  • Keep a card to four fields or fewer, and put it after the core content; more belongs in the advanced view (Built for Light, rule 2).

The forms

Form codeEntity interfaceContainers
productMagento\Catalog\Api\Data\ProductInterfacemrx.product.form.main.after_pricing, mrx.product.form.main.bottom, mrx.product.form.aside.bottom
categoryMagento\Catalog\Api\Data\CategoryInterfacemrx.category.form.main.bottom, mrx.category.form.aside.bottom
cms_pageMagento\Cms\Api\Data\PageInterfacemrx.cms_page.form.main.bottom, mrx.cms_page.form.aside.bottom
cms_blockMagento\Cms\Api\Data\BlockInterfacemrx.cms_block.form.main.bottom
discountMagento\SalesRule\Api\Data\RuleInterfacemrx.discount.form.main.bottom, mrx.discount.form.aside.bottom
customer_newMagento\Customer\Api\Data\CustomerInterfacemrx.customer.new.main.bottom
customerMagento\Customer\Api\Data\CustomerInterfacemrx.customer.contact.form.bottom

The generated reference lists the same with their versions. Order views have no form pipeline: a card on an order has its own controller (Order and customer pages).

Steps

1. The extension class

One class implements the form interfaces:

  • FormExtensionInterface: load() gives the card its values, validate() returns messages per field, save() writes your own tables inside the transaction and returns what the page gets back as ext.<code>.
  • DeclaresFieldsInterface: getFields() declares the fields, so ExtensionCard draws them without a template.
  • AppliesToEntityInterface: apply() sets the values on the entity before the editor saves it.
  • AfterCommitInterface (0.8.0; every Light editor since 0.11.0): afterCommit() starts work once the entity is committed (Start work after the save).
app/code/Mrx/Light/Api/Form/AppliesToEntityInterface.php
public function apply(FormContextInterface $context, array $input, object $entity): void;

FormContextInterface tells your class which form, entity and store view it works on, and CurrentFormInterface::get() gives the same to any block on the page.

The golden example's product field is an admin-only product attribute, set in apply(); save() returns null because the product's own save stores it:

docs/magerex-light/examples/Acme_LightExample/Model/Form/NoteField.php
public function save(FormContextInterface $context, array $input): ?array

The fields getFields() returns:

Prop

Type

2. Register it

The pool form_extensions is keyed by form code, then by your extension code, with the class and the ACL resource that may see and save the card:

app/code/Acme/LightProof/etc/adminhtml/di.xml
<item name="acme_proof" xsi:type="array">
    <item name="extension" xsi:type="object">Acme\LightProof\Model\ProofField\Proxy</item>
    <item name="resource" xsi:type="string">Acme_LightProof::manage</item>
</item>

3. The card

Mrx\Light\Block\ExtensionCard in one of the form's containers draws the declared fields. The card renders inside the editor's <form>: a card of your own never prints a <form>, and gives every button type="button", or a click saves the whole editor. Its inputs are named ext[<code>][<field>], so the save bar tracks them and the editor posts them to your class:

app/code/Acme/LightProof/view/adminhtml/layout/light_products_form.xml
<referenceContainer name="mrx.product.form.main.after_pricing">

4. JS hooks

The card's js argument loads a RequireJS module that registers hooks for the form and your code with Mrx_Light/js/form-hooks: validate checks in the browser before anything is posted, payload adds values, saved runs after the save. Acme_LightProof refuses the value "jsfail" in the browser, before any request, and adds js to every save:

app/code/Acme/LightProof/view/adminhtml/web/js/proof-hooks.js
hooks.register('product', 'acme_proof', {

After a save the form fires mrx:form-saved with formCode, entityId and response (Events, JS modules and #mrx-config keys).

How a save runs

The browser checks first, then the server runs every extension of the form inside the editor's database transaction. This is the product editor; the other six forms run the same steps, and since 0.11.0 they call afterCommit() too, after their commit and, where they reindex, after the reindex:

Where validate() runs differs per form: the product save runs it inside the transaction, the category and discount editors in their controller before the save, and the CMS and customer editors in their service before the transaction. A message from validate() always stops the save.

Start work after the save

Some work must wait until the product is in the database for good: a background job that reads it, a call to another system, a run that translates it. save() runs inside the editor's transaction, so its failure takes the product back with it. Implement AfterCommitInterface next to FormExtensionInterface for that work:

app/code/Mrx/Light/Api/Form/AfterCommitInterface.php
public function afterCommit(FormContextInterface $context, array $input, bool $created): ?array;
  • It runs only when your namespace ext[<code>] was posted, after the editor's commit and the reindex, and never after a rollback. In a language view it runs for an extension with language fields, with the store view in the context and only those fields in $input.
  • $context carries the saved product after a new product's save too, so getEntityId() can't tell a new product from an edit. $created is true only when this save created the product. Check it when your work must start once per product, not on every save.
  • An exception is logged as a warning and never fails the save, because the product is committed already. Catch what you can and return a message for the page instead.
  • What it returns joins your ext.<code> in the save response, over the keys your save() returned, so your saved hook reads both.
  • The class is still a form extension: its validate() and save() run inside the transaction and its load() on every product page. Keep them cheap; a class that only works after the save returns [] from load() and validate() and null from save().
  • The product editor has called it since 0.8.0. Since 0.11.0 so do the editors of the forms category, discount, cms_page, cms_block, customer_new and customer: the category editor after its reindex, the others right after the commit. On a 0.8 to 0.10 install an afterCommit() on those forms never runs, so a module that supports them needs an observer on <entity>_save_commit_after there. The language view of the category editor does not call it.

Per-language fields

A card never shows in the product editor's language view by default: extension values belong to the product, not to a store view. A module whose fields hold a value per store view, such as a store-scoped attribute for a USP line, opts in with DeclaresLanguageFieldsInterface next to DeclaresFieldsInterface:

app/code/Mrx/Light/Api/Form/DeclaresLanguageFieldsInterface.php
public function getLanguageFields(FormContextInterface $context): array;
app/code/Mrx/Light/Api/Form/DeclaresLanguageFieldsInterface.php
public function loadLanguage(FormContextInterface $context): array;
  • getLanguageFields() returns the codes of the declared fields that differ per store view. In a language view the card draws only those fields, each with "Use default". An extension without the interface shows nothing there, as before.
  • loadLanguage() returns ['own' => ..., 'default' => ...]. own holds the fields this store view has a value for; a field missing from it shows as "Use default". default holds the default values the field falls back to. getStoreId() is the store view and getEntity() the product or category loaded in it.
  • The language save runs only the extensions with language fields that were posted. validate(), apply(), save() and, in the product editor, afterCommit() get only the language fields. A field on "Use default", or posted empty, arrives as null; a field the page didn't post is left out and keeps its store value. No field is required in a language view.
  • Light reads each field after apply() ran, whether apply() changed it with setData() or with setCustomAttribute(). The field code must be a store-scoped attribute your module owns: Magento's own translated texts (name, description, short_description, meta_title, meta_description, url_key) are skipped. Every code getLanguageFields() returns must also be declared in getFields().
  • The card's js hooks module is not loaded in the product editor's language view, because only the language fields are on the page.
  • A card shows in the language view from any container of the editor (mrx.product.form.main.after_pricing, main.bottom, aside.bottom and the category editor's two), drawn in the main column.
  • For that store view Light writes the value the field holds after apply() into the store-scoped attribute of the same code (not a website or global one), and deletes the store row of a null one. The category editor writes only what changed: a value equal to the store view's current one and a null for a field with no store row of its own cause no write. Values that live elsewhere are yours to save in save(), and to remove there when the field arrives as null. A global attribute is never written from a language view.
  • A toggle is drawn as a Yes and No choice in a language view, because a switch can't show a default it doesn't hold.

The category editor shows every language on one page, so it draws one card per language panel and the language fields post under store[<id>]. validate(), apply() and save() run for each store view that posted fields, inside the category's own transaction (also for a new category), and the card for the default language keeps the form hooks. getEntity() is the category loaded in that store view, as in the product editor. One difference: the language panels of the category editor don't call afterCommit(); the main save does, after its reindex.

The example module Acme_LightExample has a store-scoped tagline next to its note, with NoteField implementing both interfaces.

What the admin sees

The product editor with the proof module's card after the pricing

  • Simple mode. The card on the editor, after the core content. A message from validate() shows under its field, next to the editor's own messages, and nothing is saved.
  • Language view. The card shows only the fields of an extension with language fields, each with "Use default". Switching it on shows the default value and removes the store view's own value when the merchant saves.
  • Advanced mode. The stock form, without the card. A value set through apply() is an attribute, so the stock form, REST, import and "Duplicate" see it.

Let AI fill your field

On a new product the editor offers "Let AI fill in your product" (Mrx_Ai): a photo and a few words, and the AI writes the empty fields. A field of your card can take part in two small steps, and your card needs no AI code of its own.

  1. Name the text in Disrex_AiCatalog's draftFields pool, in your global etc/di.xml, so the model writes it: label, kind (line, text, html or url_key), max, rule (the model's line for the field; {{max}} is replaced) and sortOrder.
  2. Say which input of your card receives it, with an item of Light's pool ai_draft_inputs in etc/adminhtml/di.xml: draft_key (the draftFields key), extension (your extension code) and field (the field of getFields()), so the input is ext[<extension>][<field>].
<type name="Mrx\Ai\Model\DraftInputs">
    <arguments>
        <argument name="inputs" xsi:type="array">
            <item name="acme_proof_note" xsi:type="array">
                <item name="draft_key" xsi:type="string">acme_proof_note</item>
                <item name="extension" xsi:type="string">acme_proof</item>
                <item name="field" xsi:type="string">note</item>
            </item>
        </argument>
    </arguments>
</type>

The draft script reads the input for emptiness and posts the key only while that input is empty. It fills the input like typed text and fires input and change on it, so your own form-hooks (validate, payload) see the value, and the card's note and Undo all cover it. Nothing is saved before the merchant saves, and a filled field is never overwritten. When the merchant saves, the text your card posted is recorded in the translation log as filled in by AI (AI in your module, step 11). A field you draw yourself, with no card, uses the events mrx:ai:draft-request and mrx:ai:drafted instead (AI in your module, step 11). Price, stock, SKU, weight and tax are never filled, whatever a pool says.

ACL

The card, its values and its save need the item's resource. A posted ext[<code>] without it is ignored and logged.

Check it

  • bin/magento mrx:light:doctor --module=<your module>: unknown_reference with kind form catches a misspelled form code, unknown_container a wrong container.
  • ?mrx_slots=1 in developer mode outlines the containers on the page.
  • tests/playwright/light-proof.spec.ts test 4 is the test to copy.

Pitfalls

  • Where the data lives. A value of the entity is an attribute set in apply(), so REST, import, "Duplicate" and the stock form see it. An own table is only for data that isn't a property of the entity, with a foreign key onDelete CASCADE and its own service. A storefront-visible or filterable user-defined attribute already shows in the Details card. The pipeline runs only in the Light editors, so a rule that must always hold belongs in your service or the attribute's backend model.
  • The module's own product-form logic (ui_component modifiers, plugins on the stock Product\Save controller) doesn't run on a Light save.
  • save() only writes the database. Emails and calls to other systems belong after the commit: in afterCommit() (Start work after the save); on a 0.8 to 0.10 install, an observer on <entity>_save_commit_after does it for the forms other than the product form. Both run only after the commit and never after a rollback.
  • Set variant values in the advanced view. An AdvancedHint in mrx.product.form.main.after_pricing can say so.
  • When a field becomes required later, fill it for existing entities in a data patch.

Last updated on

On this page