
Hyva Cms Custom Field
- 518 installs
- 78 repo stars
- Updated July 31, 2026
- hyva-themes/hyva-ai-tools
hyva-cms-custom-field is an agent skill that adds and renders Hyvä CMS custom fields in Magento storefronts for developers who need merchants to manage extra content blocks, metadata, and merchandising data.
About
hyva-cms-custom-field in hyva-themes/hyva-ai-tools walks developers through defining, registering, and rendering custom fields in the Hyvä CMS layer on Magento storefronts. The skill covers merchant-managed content blocks beyond default page builder fields, including supplemental metadata and merchandising data that must surface in Hyvä templates. Agents guide field schema creation, admin configuration, and Tailwind-friendly frontend rendering patterns consistent with Hyvä Theme conventions. Developers reach for hyva-cms-custom-field when a Magento shop needs flexible CMS-driven sections—promotional bands, spec tables, SEO metadata, or category merchandising slots—without hard-coding copy in layout XML or PHP blocks. Output includes field definitions wired into Hyvä CMS and template snippets that read those values on the storefront. Triggers include Hyvä CMS custom field, Magento content block extension, merchant-editable merchandising data, and rendering extra CMS attributes in Hyvä pages. The workflow assumes an existing Hyvä + Magento codebase rather than greenfield theme scaffolding.
- Hyvä theme
- Magento CMS
- custom fields
- Tailwind templates
- ecommerce storefront
Hyva Cms Custom Field by the numbers
- 518 all-time installs (skills.sh)
- +15 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #616 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/hyva-themes/hyva-ai-tools --skill hyva-cms-custom-fieldAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 518 |
|---|---|
| repo stars | ★ 78 |
| Last updated | July 31, 2026 |
| Repository | hyva-themes/hyva-ai-tools ↗ |
How do you add custom fields in Hyvä CMS?
Add and render Hyvä CMS custom fields in Magento storefronts so merchants can manage extra content blocks, metadata, and merchandising data.
Who is it for?
Magento developers on Hyvä Theme who need merchant-editable CMS fields for content blocks, metadata, or merchandising data on the storefront.
Skip if: Non-Magento stacks, Luma-only themes without Hyvä CMS, or projects that only need generic React component libraries unrelated to Magento admin.
When should I use this skill?
User asks to add Hyvä CMS custom fields, render merchant content blocks in Hyvä templates, or extend Magento merchandising metadata on the storefront.
What you get
Hyvä CMS custom field schema, admin configuration, and storefront template rendering for merchant-managed content and metadata.
- CMS custom field definitions
- Admin field configuration
- Hyvä template rendering snippets
Files
Hyvä CMS Custom Field Type Creator
Overview
This skill guides the creation of custom field types and field handlers for Hyvä CMS components. Custom field types extend the built-in field types (text, textarea, select, etc.) with specialized input controls for the CMS editor interface.
Two types of custom fields: 1. Basic Custom Field Type: Custom input control with direct data entry (e.g., date range, color picker, custom validation) 2. Field Handler: Enhanced UI with complex interactions (e.g., product selector with images, searchable dropdown, link configuration modal)
Command execution: For commands that need to run inside the development environment (e.g., bin/magento), use the hyva-exec-shell-cmd skill to detect the environment and determine the appropriate command wrapper.
Workflow
Step 1: Module Selection
If not already specified in the prompt, determine where to create the custom field type:
Option A: New Module
Use the hyva-create-module skill with:
dependencies:["Hyva_CmsBase", "Hyva_CmsLiveviewEditor"]composer_require:{"hyva-themes/commerce-module-cms": "^1.0"}
Option B: Existing Module
Verify the module has required dependencies:
Hyva_CmsBaseandHyva_CmsLiveviewEditorinetc/module.xmlhyva-themes/commerce-module-cmsincomposer.json
Add missing dependencies if needed.
Step 2: Field Type Details
Gather information about the custom field type:
1. Field type name (lowercase identifier, e.g., date_range, product_selector, color_picker) 2. Purpose (what data does it collect?) 3. UI pattern:
- Basic field: Simple input with validation (date picker, pattern input, enhanced text field)
- Inline handler: Enhanced control in field area (searchable dropdown, color picker)
- Modal handler: Separate dialog for complex selection (product selector, link builder, media gallery)
4. Data structure (simple string, JSON object, array?) 5. Validation requirements (pattern, required, custom rules?)
Step 3: Implementation Pattern Selection
Based on the UI pattern identified in Step 2:
Pattern A: Basic Custom Field Type
For simple inputs with custom HTML5 validation or specialized input controls:
- Single template file for the field
- No separate handler modal
- Example: Date range selector, custom pattern validation, slider input
Pattern B: Inline Field Handler
For enhanced controls that remain in the field area:
- Single template file with Alpine.js component
- No separate handler modal
- Example: Searchable select dropdown, color picker with swatches
Pattern C: Modal-Based Field Handler
For complex selection interfaces requiring more space:
- Field template (displays selection + trigger button)
- Handler modal template (separate dialog with full UI)
- Layout XML registration for the handler
- Example: Product selector, link configuration, media gallery
See references/handler-patterns.md for detailed implementation patterns and code examples for each type.
Step 4: Generate Field Template
Create the field template at view/adminhtml/templates/field-types/[field-type-name].phtml.
Required template elements: 1. Field container with proper ID: field-container-{uid}_{fieldName} 2. Input element(s) with name: {uid}_{fieldName} 3. Validation messages container: validation-messages-{uid}_{fieldName} 4. updateWireField() or updateField() call on value change 5. Error state handling via $magewire->errors 6. IMPORTANT: Use null coalescing for field value: $block->getData('value') ?? '' (NOT type casting)
Use the appropriate template from assets/templates/:
basic-field.phtml.tpl- Basic custom field typeinline-handler.phtml.tpl- Inline enhanced controlmodal-field.phtml.tpl- Modal handler field template
See references/template-requirements.md for detailed template requirements and patterns.
Step 5: Generate Handler Modal (if needed)
For modal-based handlers only, create the handler template at view/adminhtml/templates/handlers/[handler-name]-handler.phtml.
Handler modal structure: 1. <dialog> element with Alpine.js component and open:flex class (NOT static flex) 2. Listen for initialization event from field template 3. Implement selection UI (search, filters, grid, etc.) 4. Dispatch editor-change event on save
Use assets/templates/modal-handler.phtml.tpl as the starting point.
See references/handler-communication.md for event protocols and data exchange patterns.
Step 6: Register Field Type
Add registration to etc/adminhtml/di.xml:
<type name="Hyva\CmsLiveviewEditor\Model\CustomField">
<arguments>
<argument name="customTypes" xsi:type="array">
<item name="[field_type_name]" xsi:type="string">
[Vendor]_[Module]::field-types/[field-type-name].phtml
</item>
</argument>
</arguments>
</type>Step 7: Register Handler Modal (if needed)
For modal-based handlers only, create or update view/adminhtml/layout/liveview_editor.xml:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="before.body.end">
<block name="[handler_name]_handler"
template="[Vendor]_[Module]::handlers/[handler-name]-handler.phtml"/>
</referenceContainer>
</body>
</page>Note: Inline handlers do NOT require layout XML registration.
Step 8: Usage Example
Provide an example of using the custom field type in components.json:
{
"my_component": {
"label": "My Component",
"content": {
"[field_name]": {
"type": "custom_type",
"custom_type": "[field_type_name]",
"label": "Field Label",
"attributes": {
"required": true,
"pattern": ".*"
}
}
}
}
}Resources
references/template-requirements.md
Complete reference for custom field type template requirements:
- Required markup patterns and element IDs
- Field container structure
- Validation message containers
- Field value update methods (
updateWireFieldvsupdateField) - HTML5 validation attributes
- Error state handling
Read this file when implementing the field template to ensure proper integration with the CMS editor.
references/handler-patterns.md
Implementation patterns for all three custom field types:
- Basic custom field type (simple input)
- Inline field handler (enhanced control)
- Modal-based field handler (dialog selection)
Each pattern includes:
- Complete code examples
- When to use each pattern
- Alpine.js component structure
- Data flow and state management
Read this file when selecting the implementation pattern and writing the template code.
references/handler-communication.md
Event protocols and data exchange for field handlers:
- Initialization event structure
- Save event structure
- Field value encoding/decoding
- Error handling patterns
- Common pitfalls and solutions
Read this file when implementing handler modals to understand the communication protocol.
references/built-in-handlers.md
Reference for Hyvä CMS built-in field handlers:
- Product Handler (modal-based, image grid selection)
- Link Handler (modal-based, multi-type link config)
- Searchable Select (inline enhanced dropdown)
Each includes:
- Location in Hyvä CMS module
- Key features and patterns
- Usage examples
- Code to examine for patterns
Read this file when looking for implementation examples or patterns to copy.
assets/templates/basic-field.phtml.tpl
Template for basic custom field types with custom validation or input controls.
Placeholders:
{{FIELD_TYPE_NAME}}- Custom field type identifier{{FIELD_INPUTS}}- Input element(s) HTML{{VALIDATION_LOGIC}}- Custom validation JavaScript (optional)
assets/templates/inline-handler.phtml.tpl
Template for inline enhanced controls (searchable dropdown, color picker, etc.).
Placeholders:
{{HANDLER_NAME}}- Alpine.js component name{{HANDLER_LOGIC}}- Alpine.js component implementation{{HANDLER_UI}}- Enhanced control HTML
assets/templates/modal-field.phtml.tpl
Field template for modal-based handlers (trigger button + hidden input).
Placeholders:
{{EVENT_NAME}}- Custom event name to dispatch{{BUTTON_LABEL}}- Button text{{DISPLAY_VALUE}}- Current selection display
assets/templates/modal-handler.phtml.tpl
Handler modal template for modal-based selection interfaces.
Placeholders:
{{HANDLER_NAME}}- Alpine.js component name{{MODAL_TITLE}}- Dialog header text{{SELECTION_UI}}- Selection interface HTML{{SAVE_LOGIC}}- Save button logic
Important Guidelines
Core Requirements
1. Template Requirements: All custom field types must follow required markup patterns (container ID, input name, validation messages) 2. Handler Registration: Modal handlers need layout XML registration; inline handlers do not 3. Validation: Apply HTML5 validation attributes via $filteredAttributes for automatic validation 4. Alpine Components: If using custom Alpine components, keep input fields outside the component and update via vanilla JS 5. Built-In Examples: Reference built-in handlers in Hyva_CmsLiveviewEditor::page/js/ for proven patterns
Accurate Patterns from Codebase
Based on built-in Hyvä CMS handler implementations:
1. Event Naming Convention: Use toggle-{type}-select pattern
- ✅ Correct:
toggle-product-select,toggle-link-select,toggle-category-select - ❌ Incorrect:
toggle-product-handler,toggle-link-handler
2. Handler Function Naming: Use init{Type}Select() pattern
- ✅ Examples:
initProductSelect(),initLinkSelect(),initCategorySelect()
3. Field Value Update Methods:
- Use `updateWireField` (default): Products, Link, Category handlers
- Triggers immediate server-side validation via Magewire
- Keeps component state synchronized
- Use `updateField` (specialized): Image handler, debounced inputs (color, range)
- Updates preview without server round-trip
- Defers validation until save
4. JSON Encoding Pattern: All complex data (arrays, objects) must be JSON-encoded
// Field template
value="<?= $escaper->escapeHtmlAttr(json_encode($fieldValue)) ?>"
// Handler initialization
const data = JSON.parse(fieldValue);
// @change handler
@change="updateWireField(..., JSON.parse($event.target.value))"5. wire:ignore for Livewire Compatibility: Searchable select uses wire:ignore wrapper
<div wire:ignore>
<div x-data="initSearchableSelect(...)">
<!-- Alpine component -->
</div>
</div>6. Separate Handler Files: Even inline handlers may have separate function files
- Field template:
liveview/field-types/searchable_select.phtml - Handler function:
page/js/searchable-select-handler.phtml
7. Icons View Model: Use for UI elements
/** @var Icons $icons */
$icons = $viewModels->require(Icons::class);
<?= /** @noEscape */ $icons->trashHtml('', 22, 22) ?>8. FieldTypes View Model: Use for attribute filtering
/** @var FieldTypes $fieldTypes */
$fieldTypes = $viewModels->require(FieldTypes::class);
$filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes);
// Or for specific attributes:
$filteredAttributes = $fieldTypes->getAttributesByKeys($attributes, ['required', 'data-required']);9. CRITICAL: Layout XML referenceContainer: Handler modals MUST use before.body.end container
- ✅ Correct:
<referenceContainer name="before.body.end"> - ❌ Incorrect:
<referenceContainer name="content"> - The
before.body.endcontainer ensures the handler modal is loaded at the end of the page body, which is required for proper Alpine.js initialization and modal functionality
10. CRITICAL: Field Value Type Handling: NEVER use type casting for field values, always use null coalescing operator
- ✅ Correct:
$fieldValue = $block->getData('value') ?? ''; - ❌ Incorrect:
$fieldValue = (string) $block->getData('value'); - Type casting
(string)will fail when value isnull, causing PHP errors - Use
?? ''for string values,?? []for array values, or appropriate default for your data type - Reference: See built-in field types like
category.phtmlwhich use?? []pattern
11. CRITICAL: Dialog Modal Classes: Handler modals must use open:flex not static flex class
- ✅ Correct:
<dialog class="... open:flex flex-col"> - ❌ Incorrect:
<dialog class="... flex flex-col">(modal always visible) - The
open:prefix applies styles only when dialog is open (native HTML dialog state) - Reference: See built-in handlers like
category-handler.phtmlwhich useopen:flex flex-col
12. CRITICAL: Complex Data Type Handling: For fields storing JSON/array data, handle BOTH array and string types
- Field values may be returned as already-decoded arrays OR as JSON strings (depends on storage/context)
- ✅ Correct pattern:
$data = ['default' => 'structure'];
if ($fieldValue) {
if (is_array($fieldValue)) {
$data = $fieldValue; // Already decoded
} elseif (is_string($fieldValue)) {
$decoded = json_decode($fieldValue, true);
if (is_array($decoded)) {
$data = $decoded;
}
}
}
// When outputting to hidden input, ALWAYS ensure it's a JSON string
$fieldValueJson = is_array($fieldValue) ? json_encode($fieldValue) : $fieldValue;- ❌ Incorrect:
json_decode($fieldValue)without type checking (fails if value is already an array) - ❌ Incorrect: Using array directly in
valueattribute without JSON-encoding first
<!-- Copyright © Hyvä Themes https://hyva.io. All rights reserved. Licensed under OSL 3.0 -->
<?php
/**
* Basic Custom Field Type Template
*
* Use this template for simple custom field types with specialized validation
* or input controls that don't require complex UI interactions.
*
* Replace placeholders:
* - {{FIELD_INPUTS}} - Your input element(s) HTML
* - {{CUSTOM_VALIDATION}} - Optional custom validation logic
*/
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\CmsLiveviewEditor\ViewModel\Adminhtml\FieldTypes;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
/** @var ViewModelRegistry $viewModels */
/** @var FieldTypes $fieldTypes */
$fieldTypes = $viewModels->require(FieldTypes::class);
// Component and field identifiers passed by Hyvä CMS editor
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
// Options from component configuration (if using options like select)
$options = (array) $block->getData('options');
// HTML attributes from component configuration (e.g., validation patterns)
$attributes = (array) $block->getData('attributes') ?? [];
$filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes);
// Validation state from Magewire component
$hasError = isset($magewire->errors[$uid][$fieldName]);
$errorMessage = $hasError ? $magewire->errors[$uid][$fieldName] : '';
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
{{FIELD_INPUTS}}
<!-- Example:
<input type="text"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)"
class="form-input <?= $hasError ? 'error field-error' : '' ?>"
<?php foreach ($filteredAttributes as $attr => $attrValue): ?>
<?= $escaper->escapeHtmlAttr($attr) ?>="<?= $escaper->escapeHtmlAttr($attrValue) ?>"
<?php endforeach; ?>>
-->
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none">
<?php if ($hasError): ?>
<li class="error-message text-red-600 text-sm mt-1">
<?= $escaper->escapeHtml($errorMessage) ?>
</li>
<?php endif; ?>
</ul>
</div>
{{CUSTOM_VALIDATION}}
<!-- Optional: Add custom validation logic here
<script>
// Custom validation or UI enhancements
</script>
-->
<?php
/**
* Inline Field Handler Template
*
* Use this template for enhanced controls that remain in the field area
* (searchable dropdowns, color pickers, inline selectors).
*
* Replace placeholders:
* - {{HANDLER_NAME}} - Alpine.js component function name (e.g., searchableSelectHandler)
* - {{HANDLER_UI}} - Your enhanced control HTML
* - {{HANDLER_LOGIC}} - Alpine.js component implementation
*/
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
use Hyva\Theme\Model\ViewModelRegistry;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
/** @var ViewModelRegistry $viewModels */
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
$options = (array) $block->getData('options');
$hasError = isset($magewire->errors[$uid][$fieldName]);
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
<div x-data="{{HANDLER_NAME}}(
'<?= $escaper->escapeJs($uid) ?>',
'<?= $escaper->escapeJs($fieldName) ?>',
'<?= $escaper->escapeJs($fieldValue) ?>',
<?= $escaper->escapeHtmlAttr(json_encode($options)) ?>
)"
x-on:click.outside="open = false"
class="relative">
{{HANDLER_UI}}
<!-- Example: Searchable dropdown
<button type="button"
@click="open = !open"
class="w-full flex items-center justify-between px-3 py-2 border rounded-md">
<span x-text="selectedLabel || 'Select...'"></span>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</button>
<div x-show="open" x-transition class="absolute z-50 w-full mt-1 bg-white border rounded-md shadow-lg">
<input type="text"
x-model="search"
@input="filterOptions()"
placeholder="Search..."
class="w-full px-3 py-2 border-b">
<div class="max-h-60 overflow-auto">
<template x-for="option in filteredOptions" :key="option.value">
<button type="button"
@click="selectOption(option)"
class="w-full text-left px-4 py-2 hover:bg-gray-100">
<span x-text="option.label"></span>
</button>
</template>
</div>
</div>
-->
</div>
<!-- Hidden input for field name requirement -->
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>">
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none"></ul>
</div>
<script>
{{HANDLER_LOGIC}}
/* Example: Searchable select component
function {{HANDLER_NAME}}(uid, fieldName, initialValue, options) {
return {
open: false,
search: '',
selectedValue: initialValue,
selectedLabel: '',
allOptions: options,
filteredOptions: options,
init() {
this.updateSelectedLabel();
},
filterOptions() {
const searchLower = this.search.toLowerCase();
this.filteredOptions = this.allOptions.filter(option =>
option.label.toLowerCase().includes(searchLower)
);
},
selectOption(option) {
this.selectedValue = option.value;
this.selectedLabel = option.label;
this.open = false;
this.search = '';
this.filteredOptions = this.allOptions;
// Update field value using global function
updateWireField(uid, fieldName, option.value);
},
updateSelectedLabel() {
const selected = this.allOptions.find(o => o.value === this.selectedValue);
this.selectedLabel = selected ? selected.label : '';
}
}
}
*/
</script>
<?php
/**
* Modal-Based Field Handler - Field Template
*
* Use this template for the field part of a modal-based handler.
* This template displays the current selection and a button to open the handler modal.
*
* Replace placeholders:
* - {{EVENT_NAME}} - Custom event name to dispatch (e.g., toggle-product-select)
* - {{BUTTON_LABEL}} - Button text (e.g., "Select Products")
* - {{DISPLAY_VALUE}} - Code to display current selection summary
*/
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
// Get custom attributes from component configuration
$attributes = (array) $block->getData('attributes') ?? [];
$hasError = isset($magewire->errors[$uid][$fieldName]);
// Parse current field value for display (handle both array and JSON string)
// Adjust this based on your data structure
$selectedItems = [];
if ($fieldValue) {
if (is_array($fieldValue)) {
$selectedItems = $fieldValue;
} elseif (is_string($fieldValue)) {
try {
$decoded = json_decode($fieldValue, true);
if (is_array($decoded)) {
$selectedItems = $decoded;
}
} catch (\Exception $e) {
// Keep default empty array
}
}
}
// Ensure field value is always a JSON string for the hidden input
$fieldValueJson = is_array($fieldValue) ? json_encode($fieldValue) : $fieldValue;
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
{{DISPLAY_VALUE}}
<!-- Example: Display selected items summary
<div class="mb-2">
<?php if (!empty($selectedItems)): ?>
<div class="text-sm text-gray-600">
Selected: <?= count($selectedItems) ?> item<?= count($selectedItems) > 1 ? 's' : '' ?>
</div>
<div class="flex flex-wrap gap-2 mt-2">
<?php foreach ($selectedItems as $item): ?>
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-800">
<?= $escaper->escapeHtml($item['name'] ?? $item['label'] ?? 'Item') ?>
</span>
<?php endforeach; ?>
</div>
<?php else: ?>
<div class="text-sm text-gray-500">No items selected</div>
<?php endif; ?>
</div>
-->
<!-- Trigger button to open handler modal -->
<button type="button"
class="btn btn-primary"
@click="$dispatch('{{EVENT_NAME}}', {
isOpen: true,
uid: '<?= $escaper->escapeJs($uid) ?>',
fieldName: '<?= $escaper->escapeJs($fieldName) ?>',
fieldValue: document.getElementById('<?= $escaper->escapeJs("{$uid}_{$fieldName}") ?>').value
<?php foreach ($attributes as $attrKey => $attrValue): ?>
, <?= $escaper->escapeJs($attrKey) ?>: <?= json_encode($attrValue) ?>
<?php endforeach; ?>
})">
{{BUTTON_LABEL}}
</button>
<!-- Hidden input stores the field value -->
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValueJson) ?>"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)"
class="<?= $hasError ? 'error field-error' : '' ?>">
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none"></ul>
</div>
<?php
/**
* Modal-Based Field Handler - Handler Modal Template
*
* Use this template for the modal part of a modal-based handler.
* This template is registered in layout XML and rendered once on the page.
*
* Replace placeholders:
* - {{EVENT_NAME}} - Event name to listen for (e.g., toggle-product-select)
* - {{HANDLER_NAME}} - Alpine.js component function name (e.g., initProductSelectHandler)
* - {{MODAL_TITLE}} - Dialog header text
* - {{SELECTION_UI}} - Your selection interface HTML
* - {{SAVE_LOGIC}} - Additional logic in save method (optional)
*/
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
/** @var Template $block */
/** @var Escaper $escaper */
?>
<!-- IMPORTANT: Use 'open:flex' NOT 'flex' to prevent modal from always displaying -->
<dialog class="max-w-screen-xl w-screen bg-white shadow-xl rounded-lg open:flex flex-col"
style="max-height: 90vh;"
x-data="{{HANDLER_NAME}}()"
x-htmldialog="open = false"
closeby="any"
x-show="open"
x-transition
@{{EVENT_NAME}}.window="initializeModal($event.detail)">
<!-- Header -->
<div class="p-4 border-b flex items-center justify-between">
<h2 class="text-xl font-semibold"><?= $escaper->escapeHtml(__('{{MODAL_TITLE}}')) ?></h2>
<button type="button" @click="open = false" class="text-gray-500 hover:text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
</button>
</div>
<!-- Search/Filters (optional) -->
<div class="p-4 border-b">
<input type="text"
x-model="searchTerm"
@input.debounce.300ms="search()"
placeholder="Search..."
class="w-full px-4 py-2 border rounded-md">
</div>
<!-- Content Area -->
<div class="flex-1 overflow-y-auto p-4">
{{SELECTION_UI}}
<!-- Example: Grid of items
<div class="grid grid-cols-3 gap-4">
<template x-for="item in items" :key="item.id">
<div class="border rounded-lg p-4 cursor-pointer"
:class="{ 'border-blue-500 bg-blue-50': isSelected(item.id) }"
@click="toggleItem(item)">
<h3 x-text="item.name"></h3>
</div>
</template>
</div>
<div x-show="items.length === 0" class="text-center py-8 text-gray-500">
No items found
</div>
-->
</div>
<!-- Footer -->
<div class="p-4 border-t flex items-center justify-between">
<div class="text-sm text-gray-600">
<span x-text="selectedItems.length"></span> selected
</div>
<div class="flex gap-4">
<button type="button"
class="btn"
@click="open = false">
<?= $escaper->escapeHtml(__('Cancel')) ?>
</button>
<button type="button"
class="btn btn-primary"
@click="saveSelection()">
<?= $escaper->escapeHtml(__('Save')) ?>
</button>
</div>
</div>
</dialog>
<script>
function {{HANDLER_NAME}}() {
return {
open: false,
uid: null,
fieldName: null,
searchTerm: '',
items: [],
selectedItems: [],
/**
* Initialize modal when field template dispatches event
*/
initializeModal({ isOpen, uid, fieldName, fieldValue } = {}) {
// Store context
this.uid = uid;
this.fieldName = fieldName;
// Parse current field value with error handling
try {
this.selectedItems = JSON.parse(fieldValue || '[]');
} catch (e) {
console.error('Failed to parse field value:', e);
this.selectedItems = [];
}
// Load/initialize data
this.loadItems();
// Open the modal
this.open = isOpen;
},
/**
* Load items (replace with real API call)
*/
async loadItems() {
// Example: Fetch from Magento API
// const response = await fetch('/rest/V1/your-endpoint');
// this.items = await response.json();
// Mock data for demonstration
this.items = [];
},
/**
* Search/filter items
*/
search() {
// Implement search logic
this.loadItems();
},
/**
* Check if item is selected
*/
isSelected(itemId) {
return this.selectedItems.some(item => item.id === itemId);
},
/**
* Toggle item selection
*/
toggleItem(item) {
const index = this.selectedItems.findIndex(i => i.id === item.id);
if (index >= 0) {
this.selectedItems.splice(index, 1);
} else {
this.selectedItems.push(item);
}
},
/**
* Save selection and close modal
*/
saveSelection() {
{{SAVE_LOGIC}}
// Optional: Add validation here
// if (this.selectedItems.length === 0) {
// alert('Please select at least one item');
// return;
// }
// Dispatch editor-change event with correct property names
this.$dispatch('editor-change', {
name: this.uid, // IMPORTANT: use 'name' for component UID
field: this.fieldName, // IMPORTANT: use 'field' for field name
value: this.selectedItems, // Your data structure (automatically JSON-encoded)
saveState: true // Triggers Magewire sync and validation
});
// Close modal
this.open = false;
}
}
}
</script>
Built-In Field Handlers Reference
Hyvä CMS includes several built-in field handlers that serve as reference implementations and are available for use in custom components. These handlers demonstrate proven patterns and best practices for custom field types.
All built-in handlers are located in the Hyvä CMS Liveview Editor module:
- Field Templates:
Hyva_CmsLiveviewEditor::liveview/field-types/ - Handler Modals/Scripts:
Hyva_CmsLiveviewEditor::page/js/
Handler Overview
| Handler | Type | Event Name | Use Case | Key Features |
|---|---|---|---|---|
| Product | Modal | toggle-product-select | Product selection | Image grid, search, drag-and-drop ordering, active/available split |
| Link | Modal | toggle-link-select | Link configuration | Multi-type selection, entity pickers, inline label editing |
| Category | Modal | toggle-category-select | Category selection | Tree view, image support, path display, max selection limit |
| Image | Modal | toggle-image-select | Image/media selection | Media browser integration, image preview, alt text |
| Searchable Select | Inline (separate handler file) | N/A | Enhanced dropdown | Keyboard navigation, client-side filtering, wire:ignore |
Product Handler
Field Template: Hyva_CmsLiveviewEditor::liveview/field-types/products.phtml Handler Modal: Hyva_CmsLiveviewEditor::page/js/product-handler.phtml Handler Function: initProductSelect()
Overview
A modal-based handler for selecting products with visual images. Displays products in a grid with search, filtering, and a split view between selected and available products with drag-and-drop reordering using Sortable.js.
Event Protocol
Initialization Event (dispatched by field template):
$dispatch('toggle-product-select', {
isOpen: true,
uid: '<?= $escaper->escapeHtmlAttr($uid) ?>',
fieldName: '<?= $escaper->escapeHtmlAttr($fieldName) ?>',
fieldValue: '<?= $escaper->escapeJs(json_encode($fieldValue)) ?>' // JSON string
})Handler Initialization:
function initProductSelect() {
return {
async initializeModal({ isOpen, uid, fieldName, fieldValue } = {}) {
const activeProducts = JSON.parse(fieldValue); // Parse JSON string
this.uid = uid;
this.fieldName = fieldName;
this.activeProducts = activeProducts || [];
// ... initialize Sortable.js and load products
}
}
}Save Event (dispatched by handler):
$dispatch('editor-change', {
name: this.uid, // Component UID
field: this.fieldName, // Field name
value: this.activeProducts, // Array of product objects
saveState: true
})Data Structure
// Stored in field (JSON-encoded)
[
{
"id": 1,
"name": "Product Name",
"sku": "SKU001",
"thumbnail": {
"url": "https://example.com/image.jpg"
}
}
]Field Template Pattern
<input type="hidden"
value="<?= $escaper->escapeHtmlAttr(json_encode($fieldValue)) ?>"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
JSON.parse($event.target.value) // Parse JSON from handler
)">Key Features
1. Image Grid Layout: Products displayed in a grid with thumbnails 2. Search Functionality: Real-time debounced search by product name/SKU 3. Active/Available Split: Two-section layout showing selected vs available products 4. Drag-and-Drop Ordering: Reorder selected products with Sortable.js 5. API Integration: Fetches products from Magento REST API 6. Display Summary: Shows selected products with thumbnails in field area
Usage Example
{
"product_carousel": {
"label": "Product Carousel",
"content": {
"products": {
"type": "products",
"label": "Select Products"
}
}
}
}Link Handler
Field Template: Hyva_CmsLiveviewEditor::liveview/field-types/link.phtml Handler Modal: Hyva_CmsLiveviewEditor::page/js/link-handler.phtml Handler Function: initLinkSelect()
Overview
A modal-based handler for configuring links with multiple types (CMS page, category, product, custom URL, Magento page). Provides radio button selection for link types with conditional fields and searchable entity dropdowns.
Event Protocol
Initialization Event:
$dispatch('toggle-link-select', { // Note: 'toggle-link-select' not 'toggle-link-handler'
isOpen: true,
uid: '<?= $escaper->escapeHtmlAttr($uid) ?>',
fieldName: '<?= $escaper->escapeHtmlAttr($fieldName) ?>',
fieldValue: JSON.stringify(linkValues), // JSON stringified object
hideLabel: <?= $hideLabel ? 'true' : 'false' ?> // Optional config
})Data Structure
{
"type": "cms_page|category|product|custom_url|magento",
"label": "Link Text",
"value": "page-identifier-or-id",
"src": "/generated/url/path", // Generated by backend
"open_in_new_tab": false,
"prefix": "", // For custom_url type
"suffix": "",
"placeholder": ""
}Key Features
1. Multi-Type Support: CMS page, category, product, custom URL, Magento page 2. Radio Button Interface: Visual selection of link type with icons 3. Conditional Fields: Fields show/hide based on selected link type 4. Entity Selectors: Searchable dropdowns for CMS pages, categories, products 5. Inline Label Editing: Edit link text directly in field template 6. Auto URL Generation: Backend generates src from selected entity 7. Copy Label Button: Copy entity name to label field
Field Template Pattern
<div x-data="{
linkValues: null,
saveValue() {
updateWireField('<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
this.linkValues);
}
}">
<input type="hidden"
:value="JSON.stringify(linkValues)"
@change="updateWireField(...)">
<!-- Inline label editing -->
<input type="text"
x-model="linkValues.label"
@input.debounce.500="saveValue()">
<!-- Button to open handler -->
<button @click="$dispatch('toggle-link-select', {...})">
Select Link
</button>
</div>Usage Example
{
"call_to_action": {
"label": "Call to Action",
"content": {
"button_link": {
"type": "link",
"label": "Button Link",
"config": {
"hide_label": false
}
}
}
}
}Category Handler
Field Template: Hyva_CmsLiveviewEditor::liveview/field-types/category.phtml Handler Modal: Hyva_CmsLiveviewEditor::page/js/category-handler.phtml Handler Function: initCategorySelect()
Overview
A modal-based handler for selecting categories from the Magento category tree. Displays categories with optional images, hierarchical paths, and supports maximum selection limits.
Event Protocol
Initialization Event:
$dispatch('toggle-category-select', {
isOpen: true,
uid: '<?= $escaper->escapeHtmlAttr($uid) ?>',
fieldName: '<?= $escaper->escapeHtmlAttr($fieldName) ?>',
fieldValue: '<?= $escaper->escapeJs(json_encode($fieldValue)) ?>', // JSON string
maxSelected: <?= $escaper->escapeHtmlAttr($maxSelected) ?> // Optional config
})Data Structure
[
{
"id": 3,
"name": "Gear",
"path": "Default Category/Gear",
"image": "https://example.com/category.jpg" // Optional
}
]Key Features
1. Category Tree Navigation: Browse Magento category hierarchy 2. Category Images: Display category images if available 3. Path Display: Show full category path for context 4. Max Selection: Configurable limit via config.max_selected 5. Search: Filter categories by name 6. Display Cards: Show selected categories with image, name, ID, and path
Usage Example
{
"category_showcase": {
"label": "Category Showcase",
"content": {
"featured_categories": {
"type": "category",
"label": "Featured Categories",
"config": {
"max_selected": 6
}
}
}
}
}Image Handler
Field Template: Hyva_CmsLiveviewEditor::liveview/field-types/image.phtml Handler Modal: Hyva_CmsLiveviewEditor::page/js/image-handler.phtml Handler Function: initImageSelect()
Overview
A modal-based handler for selecting images from Magento media gallery. Integrates with Magento's media browser and provides image configuration options (alt text, dimensions, CSS classes).
Event Protocol
Initialization Event:
$dispatch('toggle-image-select', {
isOpen: true,
uid: '<?= $escaper->escapeHtmlAttr($uid) ?>',
fieldName: '<?= $escaper->escapeHtmlAttr($fieldName) ?>',
fieldValue: '<?= $escaper->escapeJs(json_encode($fields)) ?>' // JSON string
})Important: Image field uses `updateField` (not `updateWireField`):
<input type="hidden"
value="<?= $escaper->escapeHtmlAttr(json_encode($fields)) ?>"
@change="updateField( // Uses updateField, not updateWireField!
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
JSON.parse($event.target.value)
)">Data Structure
{
"src": "media/image.jpg",
"alt": "Alt text",
"width": 1920,
"height": 1080,
"classes": "custom-class",
"preview_url": "https://example.com/media/cache/image.jpg",
"imageOptions": {
// Additional image configuration
}
}Key Features
1. Media Browser Integration: Access Magento media gallery 2. Image Preview: Display selected image with edit overlay 3. Click-to-Edit: Entire image preview is clickable button to reopen handler 4. Alt Text: Configure alt text for accessibility 5. Image Options: Configure width, height, CSS classes 6. Cache-Busted Preview: Timestamp appended to preview URL (?rand= + time) 7. Remove Button: Overlay trash icon to clear image
Usage Example
{
"hero_banner": {
"label": "Hero Banner",
"content": {
"background": {
"type": "image",
"label": "Background Image"
}
}
}
}Searchable Select Handler
Field Template: Hyva_CmsLiveviewEditor::liveview/field-types/searchable_select.phtml Handler Script: Hyva_CmsLiveviewEditor::page/js/searchable-select-handler.phtml Handler Function: initSearchableSelect(config)
Overview
An inline enhanced control that extends the standard select field with search functionality and keyboard navigation. Renders as a custom dropdown with client-side filtering.
Important: Unlike other handlers, the searchable select handler function is defined in a separate script file (not a modal), but the field template calls it inline. The field template uses wire:ignore to prevent Livewire conflicts.
Implementation Pattern
Field Template Structure:
<div class="field-container" ...>
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
@change="updateWireField(...)">
<div wire:ignore> <!-- IMPORTANT: wire:ignore wrapper -->
<div x-data="initSearchableSelect({
uid: '<?= $escaper->escapeJs($uid) ?>',
fieldName: '<?= $escaper->escapeJs($fieldName) ?>',
initFieldValue: '<?= $escaper->escapeJs($fieldValue) ?>',
options: <?= $escaper->escapeHtml(json_encode($options)) ?>
})"
@click.away="close()">
<!-- Dropdown button and menu -->
</div>
</div>
</div>Handler Script (separate file in page/js/):
function initSearchableSelect(config) {
return {
uid: config.uid,
fieldName: config.fieldName,
state: false, // Dropdown open/close
filter: '',
list: config.options.map((item, index) => ({
id: `${item.value}_${index}`,
value: item.value,
label: item.label
})),
selectedKey: null,
selectedLabel: null,
init() {
// Update hidden input when selection changes
this.$watch('selectedKey', (id) => {
const selectedItem = this.list.find(item => item.id === id);
const value = selectedItem ? selectedItem.value : '';
document.getElementById(`${this.uid}_${this.fieldName}`).value = value;
document.getElementById(`${this.uid}_${this.fieldName}`).dispatchEvent(new Event('change'));
});
},
// Methods: toggle(), close(), select(), navigateDown(), navigateUp(), etc.
}
}Data Structure
// Simple string value
"option_value"Key Features
1. Separate Handler File: Handler function in separate script file, not inline 2. wire:ignore: Uses Livewire's wire:ignore to prevent state conflicts 3. Direct DOM Manipulation: Updates hidden input via vanilla JS and dispatches change 4. Search Filtering: Client-side filtering through options 5. Keyboard Navigation: Arrow keys, Enter, Escape with focus management and scroll-into-view 6. Click Outside: Closes dropdown when clicking outside 7. Accessibility: ARIA attributes (listbox, option, selected, controls) 8. Alpine $watch: Watches selection and updates hidden input
Usage Example
{
"custom_component": {
"label": "Custom Component",
"content": {
"style": {
"type": "searchable_select",
"label": "Style Variant",
"options": [
{ "value": "default", "label": "Default" },
{ "value": "primary", "label": "Primary Blue" },
{ "value": "secondary", "label": "Secondary Gray" }
]
}
}
}
}Using Built-In Handlers in Custom Components
Built-in handlers can be used directly in custom components by specifying the appropriate field type.
Product Handler
{
"products": {
"type": "products",
"label": "Select Products"
}
}Link Handler
{
"link": {
"type": "link",
"label": "Button Link",
"config": {
"hide_label": false
}
}
}Category Handler
{
"categories": {
"type": "category",
"label": "Select Categories",
"config": {
"max_selected": 10
}
}
}Image Handler
{
"image": {
"type": "image",
"label": "Hero Image"
}
}Searchable Select
{
"variant": {
"type": "searchable_select",
"label": "Variant",
"options": [
{ "value": "a", "label": "Option A" },
{ "value": "b", "label": "Option B" }
]
}
}Key Implementation Patterns
Event Naming Convention
All modal-based handlers follow the pattern toggle-{type}-select:
toggle-product-selecttoggle-link-selecttoggle-category-selecttoggle-image-select
Handler Function Naming
Handler functions follow the pattern init{Type}Select():
initProductSelect()initLinkSelect()initCategorySelect()initImageSelect()initSearchableSelect(config)(takes config parameter)
updateField vs updateWireField
Use `updateWireField` (most handlers):
- Products, Link, Category handlers
- Triggers server-side validation immediately
- Sends value to server via Magewire
Use `updateField` (specialized cases):
- Image handler
- Color, Range handlers (with debounce)
- Updates preview without server round-trip
- Value persists locally until save
JSON Encoding Pattern
All complex data (arrays, objects) is JSON-encoded in field values:
In Field Template:
value="<?= $escaper->escapeHtmlAttr(json_encode($fieldValue)) ?>"In Handler Initialization:
const data = JSON.parse(fieldValue);In @change Handler:
@change="updateWireField(..., JSON.parse($event.target.value))"wire:ignore Usage
Use wire:ignore when Alpine.js components need to persist without Livewire interference:
<div wire:ignore>
<div x-data="initSearchableSelect(...)">
<!-- Alpine component -->
</div>
</div>Examining Built-In Handler Code
To study built-in handler implementations:
Field Templates:
# From Magento root
ls vendor/hyva-themes/magento2-hyva-cms-liveview-editor/view/adminhtml/templates/liveview/field-types/Handler Modals/Scripts:
# From Magento root
ls vendor/hyva-themes/magento2-hyva-cms-liveview-editor/view/adminhtml/templates/page/js/Example: Viewing the product handler
cat vendor/hyva-themes/magento2-hyva-cms-liveview-editor/view/adminhtml/templates/page/js/product-handler.phtmlKey Takeaways
1. Event Names: Use toggle-{type}-select pattern (not toggle-{type}-handler) 2. Handler Functions: Use init{Type}Select() naming pattern 3. JSON Encoding: Always JSON-encode/decode complex field values 4. updateWireField vs updateField: Most use updateWireField, image uses updateField 5. Separate Handler Files: Modal handlers in page/js/, searchable select also separated 6. wire:ignore: Use for Alpine components to prevent Livewire conflicts 7. Icons View Model: Use Hyva\CmsLiveviewEditor\ViewModel\Icons for UI icons 8. Direct DOM Manipulation: Searchable select updates hidden input directly 9. Sortable.js: Product handler uses Sortable.js for drag-and-drop 10. Copy Patterns: Start with built-in handlers as templates for custom handlers
Field Handler Communication Protocol
This document describes the event-based communication protocol between field templates and handler modals in Hyvä CMS custom field types.
Note: This protocol applies only to modal-based field handlers (Pattern C). Inline handlers (Pattern B) and basic fields (Pattern A) do not use this event system.
Communication Flow
Field Template Handler Modal
| |
|--- Dispatch Init Event ---->|
| (toggle-handler-name) |
| |
| Initialize
| (parse data,
| open modal,
| render UI)
| |
| User makes
| selection
| |
|<--- Dispatch Save Event ----|
| (editor-change) |
| |
Update hidden input Close
Trigger Magewire sync modal
Update preview |Initialization Event
The field template dispatches a custom event to open the handler modal and pass initialization data.
Event Structure
$dispatch('toggle-handler-name', {
isOpen: true, // Boolean: open the modal
uid: 'component_123', // String: component unique ID
fieldName: 'products', // String: field name from component config
fieldValue: '[]', // String: current field value (JSON-encoded)
// ... any additional config parameters
maxSelected: 25,
allowMultiple: true
})Field Template Code
<button type="button"
class="btn btn-primary"
@click="$dispatch('toggle-product-select', {
isOpen: true,
uid: '<?= $escaper->escapeJs($uid) ?>',
fieldName: '<?= $escaper->escapeJs($fieldName) ?>',
fieldValue: document.getElementById('<?= $escaper->escapeJs("{$uid}_{$fieldName}") ?>').value,
maxProducts: <?= (int) $maxProducts ?>
})">
Select Products
</button>Key points:
- Event name should be descriptive:
toggle-{handler-name} fieldValueis read from the hidden input element- Pass any configuration from component attributes
- All values must be properly escaped
Handler Modal Listener
<dialog x-data="initProductSelectHandler()"
@toggle-product-select.window="initializeModal($event.detail)">Key points:
- Use
.windowmodifier to listen to window events - Access data via
$event.detail - Call initialization method to process data
Handler Initialization Method
initializeModal({ isOpen, uid, fieldName, fieldValue, maxProducts } = {}) {
// Store context
this.uid = uid;
this.fieldName = fieldName;
this.maxProducts = maxProducts || 10;
// Parse current field value with error handling
try {
this.selectedProducts = JSON.parse(fieldValue || '[]');
} catch (e) {
console.error('Failed to parse field value:', e);
this.selectedProducts = [];
}
// Initialize UI state
this.searchProducts();
this.resetFilters();
// Open the modal
this.open = isOpen;
}Key points:
- Always use destructuring with defaults for safety
- Always parse `fieldValue` with try/catch - it may contain invalid JSON
- Store
uidandfieldNamefor the save event - Initialize UI state before opening modal
- Set
this.openlast to trigger modal display
Save Event
The handler modal dispatches the editor-change event to update the field value and close the modal.
Event Structure
$dispatch('editor-change', {
name: this.uid, // String: component UID (NOT fieldName!)
field: this.fieldName, // String: field name (NOT name!)
value: this.selectedData, // Any: new field value (will be JSON-encoded)
saveState: true // Boolean: true triggers Magewire sync
})CRITICAL: Note the property names:
namereceives the component UID (NOT the field name)fieldreceives the field name (NOT name)
This is the correct structure. Using fieldName or incorrect property names will cause silent failures.
Handler Modal Save Method
saveProducts() {
// Dispatch event with correct property names
this.$dispatch('editor-change', {
name: this.uid, // Component UID
field: this.fieldName, // Field name
value: this.selectedProducts, // Your data structure
saveState: true
});
// Close the modal
this.open = false;
}Key points:
- Property names must match exactly:
name,field,value,saveState valuecan be any JSON-serializable data structure- Hyvä CMS automatically JSON-encodes the value when storing
- Set
saveState: trueto trigger server-side validation - Close modal after dispatching event
Data Encoding and Decoding
Field Value Format
Field values in Hyvä CMS are typically stored as strings, but may be returned as arrays depending on the context:
- Database/Storage: Values are stored as JSON strings
- Runtime/Rendering: Values may be pre-decoded as arrays by Magento/Magewire
- After editor-change event: Values are automatically JSON-encoded
IMPORTANT: Always handle BOTH array and string types when retrieving field values, as the type depends on where/when the field is accessed.
In Field Template (Display):
<?php
$fieldValue = $block->getData('value') ?? '';
// Decode for display (handle both array and JSON string)
$selectedProducts = [];
if ($fieldValue) {
if (is_array($fieldValue)) {
$selectedProducts = $fieldValue;
} elseif (is_string($fieldValue)) {
try {
$decoded = json_decode($fieldValue, true);
if (is_array($decoded)) {
$selectedProducts = $decoded;
}
} catch (\Exception $e) {
// Keep default empty array
}
}
}
?>
<!-- Display selected products -->
<?php foreach ($selectedProducts as $product): ?>
<span><?= $escaper->escapeHtml($product['name']) ?></span>
<?php endforeach; ?>
<!-- IMPORTANT: Ensure field value is JSON string for hidden input -->
<?php
$fieldValueJson = is_array($fieldValue) ? json_encode($fieldValue) : $fieldValue;
?>
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValueJson) ?>">Critical Note: Always JSON-encode array values before outputting to hidden input value attribute. Using an array directly causes "Array to string conversion" errors.
In Handler Modal (Initialize):
initializeModal({ fieldValue } = {}) {
// Always parse with error handling
try {
this.selectedProducts = JSON.parse(fieldValue || '[]');
} catch (e) {
console.error('Failed to parse field value:', e);
this.selectedProducts = [];
}
}In Handler Modal (Save):
saveProducts() {
// Hyvä CMS automatically JSON-encodes when dispatching editor-change
this.$dispatch('editor-change', {
name: this.uid,
field: this.fieldName,
value: this.selectedProducts, // Array/Object - automatically encoded
saveState: true
});
}In Component PHTML Template (Render):
<?php
$products = $block->getData('products');
// Decode for rendering
$productList = [];
if ($products) {
try {
$productList = json_decode($products, true) ?: [];
} catch (\Exception $e) {
$productList = [];
}
}
?>
<?php foreach ($productList as $product): ?>
<div class="product">
<h3><?= $escaper->escapeHtml($product['name']) ?></h3>
<p><?= $escaper->escapeHtml($product['sku']) ?></p>
</div>
<?php endforeach; ?>Data Structure Examples
Simple Array:
// Save
value: ['product-1', 'product-2', 'product-3']
// Stored as
'["product-1","product-2","product-3"]'Array of Objects:
// Save
value: [
{ id: 1, name: 'Product 1', sku: 'SKU001' },
{ id: 2, name: 'Product 2', sku: 'SKU002' }
]
// Stored as
'[{"id":1,"name":"Product 1","sku":"SKU001"},{"id":2,"name":"Product 2","sku":"SKU002"}]'Complex Object:
// Save
value: {
type: 'internal',
url: '/page/about',
title: 'About Us',
target: '_self',
attributes: {
class: 'nav-link',
rel: 'nofollow'
}
}
// Stored as
'{"type":"internal","url":"/page/about","title":"About Us","target":"_self","attributes":{"class":"nav-link","rel":"nofollow"}}'Error Handling
Invalid JSON in Field Value
Always parse with try/catch when reading field values:
initializeModal({ fieldValue } = {}) {
try {
this.data = JSON.parse(fieldValue || '[]');
} catch (e) {
console.error('Failed to parse field value:', e);
// Fallback to safe default
this.data = [];
}
}Missing Required Data
Provide defaults for all initialization parameters:
initializeModal({
isOpen = false,
uid = null,
fieldName = null,
fieldValue = '[]',
maxItems = 10
} = {}) {
// Check required params
if (!uid || !fieldName) {
console.error('Missing required parameters');
return;
}
// Continue with initialization
this.uid = uid;
this.fieldName = fieldName;
// ...
}Event Dispatch Failures
If the editor-change event doesn't update the field:
1. Check property names: Must be name, field, value, saveState (not uid, fieldName, etc.) 2. Check value serialization: Ensure value is JSON-serializable (no circular references, functions, etc.) 3. Check hidden input exists: The input with id="{uid}_{fieldName}" must exist 4. Check console for errors: Look for JavaScript errors that might prevent the event
Common Patterns
Loading Indicator
Show loading state while fetching data:
initializeModal({ isOpen, uid, fieldName, fieldValue } = {}) {
this.uid = uid;
this.fieldName = fieldName;
this.loading = true;
this.open = isOpen;
// Parse existing selection
try {
this.selectedItems = JSON.parse(fieldValue || '[]');
} catch (e) {
this.selectedItems = [];
}
// Fetch data
this.fetchData().finally(() => {
this.loading = false;
});
}Validation Before Save
Validate selection before dispatching save event:
saveSelection() {
// Validate
if (this.selectedProducts.length === 0) {
alert('Please select at least one product');
return;
}
if (this.selectedProducts.length > this.maxProducts) {
alert(`Maximum ${this.maxProducts} products allowed`);
return;
}
// Save
this.$dispatch('editor-change', {
name: this.uid,
field: this.fieldName,
value: this.selectedProducts,
saveState: true
});
this.open = false;
}Confirmation Dialog
Confirm before closing without saving:
closeModal() {
if (this.hasUnsavedChanges()) {
if (!confirm('You have unsaved changes. Close anyway?')) {
return;
}
}
this.open = false;
}Reset State on Close
Clean up state when modal closes:
// In Alpine component
watch: {
open(value) {
if (!value) {
// Modal closed - reset state
this.searchTerm = '';
this.selectedItems = [];
this.loading = false;
}
}
}Testing Checklist
When implementing modal-based field handlers, verify:
- [ ] Initialization event dispatches with correct event name
- [ ] Initialization event includes all required data (uid, fieldName, fieldValue)
- [ ] Handler modal listens with
.windowmodifier - [ ] Field value parsing has try/catch error handling
- [ ] Save event uses correct property names (
name,field,value,saveState) - [ ] Save event dispatches before closing modal
- [ ] Complex data structures JSON encode/decode correctly
- [ ] Field value persists after save and page refresh
- [ ] Preview updates immediately after save
- [ ] Validation errors display correctly
- [ ] Modal state resets properly on open/close
Built-In Handler Examples
For working examples of the communication protocol, examine these built-in handlers:
Product Handler
- Location:
Hyva_CmsLiveviewEditor::page/js/product-handler.phtml - Event:
toggle-product-select - Data: Array of product objects with id, name, sku, image
Link Handler
- Location:
Hyva_CmsLiveviewEditor::page/js/link-handler.phtml - Event:
toggle-link-handler - Data: Object with type, url, title, target, attributes
These handlers demonstrate complete implementations of the communication protocol with robust error handling and state management.
Field Handler Implementation Patterns
This document describes the three implementation patterns for custom field types in Hyvä CMS, with complete code examples and guidance on when to use each pattern.
Important Implementation Notes
Based on analysis of built-in Hyvä CMS handlers:
1. Event Naming: Modal handlers use toggle-{type}-select pattern (e.g., toggle-product-select, toggle-link-select, NOT toggle-{type}-handler) 2. Handler Functions: Use init{Type}Select() pattern (e.g., initProductSelect(), initLinkSelect()) 3. updateField vs updateWireField:
- Most handlers: Use
updateWireField(products, link, category) - triggers immediate server validation - Image handler: Uses
updateField- defers validation until save - Debounced inputs: Use
updateFieldwith@input.debounce(color, range)
4. JSON Encoding: All complex data must be JSON-encoded in hidden inputs and parsed in handlers 5. wire:ignore: Searchable select uses wire:ignore wrapper to prevent Livewire conflicts 6. Separate Handler Files: Even "inline" handlers like searchable select have handler functions in separate files in page/js/ 7. Icons View Model: Use Hyva\CmsLiveviewEditor\ViewModel\Icons for UI icons (trash, pencil, etc.)
See references/built-in-handlers.md for complete examples from the actual codebase.
Pattern Decision Tree
Do you need custom UI beyond standard HTML inputs?
├─ NO → Use built-in field types (text, select, etc.)
└─ YES → Do you need a separate dialog/modal?
├─ NO → Does it fit in the field area?
│ ├─ YES → Pattern B: Inline Field Handler
│ └─ NO → Pattern C: Modal-Based Handler
└─ YES → Pattern C: Modal-Based HandlerPattern A: Basic Custom Field Type
Use when:
- Custom HTML5 validation patterns
- Specialized input controls (date range, slider, color input)
- Simple enhancements to standard inputs
- No complex UI interactions needed
Characteristics:
- Single template file
- No Alpine.js components (or minimal Alpine for state)
- Direct input elements
- Standard field value updates
Complete Example: Date Range Field
<?php
// view/adminhtml/templates/field-types/date-range.phtml
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\CmsLiveviewEditor\ViewModel\Adminhtml\FieldTypes;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
/** @var ViewModelRegistry $viewModels */
$fieldTypes = $viewModels->require(FieldTypes::class);
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
// Parse stored value (format: "2024-01-01,2024-12-31")
$dates = $fieldValue ? explode(',', $fieldValue) : ['', ''];
$startDate = $dates[0] ?? '';
$endDate = $dates[1] ?? '';
$attributes = (array) $block->getData('attributes') ?? [];
$filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes);
$hasError = isset($magewire->errors[$uid][$fieldName]);
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
<div class="flex gap-4 items-center" x-data="{ startDate: '<?= $escaper->escapeJs($startDate) ?>', endDate: '<?= $escaper->escapeJs($endDate) ?>' }">
<div>
<label class="block text-sm mb-1">Start Date</label>
<input type="date"
x-model="startDate"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
startDate + ',' + endDate
)"
class="form-input"
<?php foreach ($filteredAttributes as $attr => $attrValue): ?>
<?= $escaper->escapeHtmlAttr($attr) ?>="<?= $escaper->escapeHtmlAttr($attrValue) ?>"
<?php endforeach; ?>>
</div>
<span class="mt-6">to</span>
<div>
<label class="block text-sm mb-1">End Date</label>
<input type="date"
x-model="endDate"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
startDate + ',' + endDate
)"
class="form-input"
<?php foreach ($filteredAttributes as $attr => $attrValue): ?>
<?= $escaper->escapeHtmlAttr($attr) ?>="<?= $escaper->escapeHtmlAttr($attrValue) ?>"
<?php endforeach; ?>>
</div>
</div>
<!-- Hidden input for field name requirement -->
<input type="hidden"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>">
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none"></ul>
</div>Registration in di.xml:
<type name="Hyva\CmsLiveviewEditor\Model\CustomField">
<arguments>
<argument name="customTypes" xsi:type="array">
<item name="date_range" xsi:type="string">
Vendor_Module::field-types/date-range.phtml
</item>
</argument>
</arguments>
</type>Usage in components.json:
{
"event_card": {
"label": "Event Card",
"content": {
"event_dates": {
"type": "custom_type",
"custom_type": "date_range",
"label": "Event Dates",
"attributes": {
"required": true
}
}
}
}
}Pattern B: Inline Field Handler
Use when:
- Enhanced UI that fits in field area
- Searchable/filterable dropdowns
- Color pickers with swatches
- Inline toggles or button groups
- Progressive disclosure UI
Characteristics:
- Single template file with Alpine.js component
- Enhanced UI rendered inline
- No separate modal
- State managed within Alpine component
- No layout XML registration needed
Complete Example: Searchable Select Handler
<?php
// view/adminhtml/templates/field-types/searchable-select.phtml
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
use Hyva\Theme\Model\ViewModelRegistry;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
/** @var ViewModelRegistry $viewModels */
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
$options = (array) $block->getData('options');
$hasError = isset($magewire->errors[$uid][$fieldName]);
// Get selected option label
$selectedLabel = '';
foreach ($options as $option) {
if ($option['value'] === $fieldValue) {
$selectedLabel = $option['label'];
break;
}
}
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
<div x-data="searchableSelectHandler(
'<?= $escaper->escapeJs($uid) ?>',
'<?= $escaper->escapeJs($fieldName) ?>',
'<?= $escaper->escapeJs($fieldValue) ?>',
<?= $escaper->escapeHtmlAttr(json_encode($options)) ?>
)"
x-on:click.outside="open = false"
class="relative">
<!-- Display button -->
<button type="button"
@click="open = !open"
class="w-full flex items-center justify-between px-3 py-2 border rounded-md bg-white <?= $hasError ? 'border-red-500' : 'border-gray-300' ?>">
<span x-text="selectedLabel || 'Select an option'"></span>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</button>
<!-- Dropdown -->
<div x-show="open"
x-transition
class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto">
<!-- Search input -->
<div class="p-2 border-b">
<input type="text"
x-model="search"
@input="filterOptions()"
placeholder="Search..."
class="w-full px-3 py-2 border rounded-md">
</div>
<!-- Options list -->
<div class="py-1">
<template x-for="option in filteredOptions" :key="option.value">
<button type="button"
@click="selectOption(option)"
class="w-full text-left px-4 py-2 hover:bg-gray-100"
:class="{ 'bg-blue-50': selectedValue === option.value }">
<span x-text="option.label"></span>
</button>
</template>
<div x-show="filteredOptions.length === 0" class="px-4 py-2 text-gray-500">
No options found
</div>
</div>
</div>
</div>
<!-- Hidden input for field name requirement -->
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>">
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none"></ul>
</div>
<script>
function searchableSelectHandler(uid, fieldName, initialValue, options) {
return {
open: false,
search: '',
selectedValue: initialValue,
selectedLabel: '',
allOptions: options,
filteredOptions: options,
init() {
this.updateSelectedLabel();
},
filterOptions() {
const searchLower = this.search.toLowerCase();
this.filteredOptions = this.allOptions.filter(option =>
option.label.toLowerCase().includes(searchLower)
);
},
selectOption(option) {
this.selectedValue = option.value;
this.selectedLabel = option.label;
this.open = false;
this.search = '';
this.filteredOptions = this.allOptions;
// Update field value
updateWireField(uid, fieldName, option.value);
},
updateSelectedLabel() {
const selected = this.allOptions.find(o => o.value === this.selectedValue);
this.selectedLabel = selected ? selected.label : '';
}
}
}
</script>Registration (same as Pattern A):
<type name="Hyva\CmsLiveviewEditor\Model\CustomField">
<arguments>
<argument name="customTypes" xsi:type="array">
<item name="searchable_select" xsi:type="string">
Vendor_Module::field-types/searchable-select.phtml
</item>
</argument>
</arguments>
</type>Pattern C: Modal-Based Field Handler
Use when:
- Complex selection interfaces requiring more space
- Product/category selectors with images
- Multi-step data entry workflows
- Link builders with multiple options
- Media galleries or file browsers
- Any UI that benefits from a dedicated modal
Characteristics:
- Two template files: field template + handler modal
- Field template: trigger button + hidden input
- Handler modal: separate dialog with full UI
- Layout XML registration required
- Event-based communication
Complete Example: Product Selector Handler
Step 1: Field Template
<?php
// view/adminhtml/templates/field-types/product-selector.phtml
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
$hasError = isset($magewire->errors[$uid][$fieldName]);
// Parse selected products (handle both array and JSON string)
$selectedProducts = [];
if ($fieldValue) {
if (is_array($fieldValue)) {
$selectedProducts = $fieldValue;
} elseif (is_string($fieldValue)) {
try {
$decoded = json_decode($fieldValue, true);
if (is_array($decoded)) {
$selectedProducts = $decoded;
}
} catch (\Exception $e) {
// Keep default empty array
}
}
}
$maxProducts = (int) ($block->getData('attributes')['max_products'] ?? 10);
// Ensure field value is always a JSON string for the hidden input
$fieldValueJson = is_array($fieldValue) ? json_encode($fieldValue) : $fieldValue;
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
<!-- Display selected products -->
<div class="mb-2">
<?php if (!empty($selectedProducts)): ?>
<div class="text-sm text-gray-600">
Selected: <?= count($selectedProducts) ?> product<?= count($selectedProducts) > 1 ? 's' : '' ?>
</div>
<div class="flex flex-wrap gap-2 mt-2">
<?php foreach ($selectedProducts as $product): ?>
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-800">
<?= $escaper->escapeHtml($product['name'] ?? 'Product #' . ($product['id'] ?? '')) ?>
</span>
<?php endforeach; ?>
</div>
<?php else: ?>
<div class="text-sm text-gray-500">No products selected</div>
<?php endif; ?>
</div>
<!-- Trigger button -->
<button type="button"
class="btn btn-primary"
@click="$dispatch('toggle-product-select', {
isOpen: true,
uid: '<?= $escaper->escapeJs($uid) ?>',
fieldName: '<?= $escaper->escapeJs($fieldName) ?>',
fieldValue: document.getElementById('<?= $escaper->escapeJs("{$uid}_{$fieldName}") ?>').value,
maxProducts: <?= (int) $maxProducts ?>
})">
<?= $escaper->escapeHtml(__('Select Products')) ?>
</button>
<!-- Hidden input stores the field value -->
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValueJson) ?>"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)"
class="<?= $hasError ? 'error field-error' : '' ?>">
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none"></ul>
</div>Step 2: Handler Modal Template
<?php
// view/adminhtml/templates/handlers/product-selector-handler.phtml
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
/** @var Template $block */
/** @var Escaper $escaper */
?>
<dialog class="max-w-screen-xl w-screen bg-white shadow-xl rounded-lg open:flex flex-col"
style="max-height: 90vh;"
x-data="initProductSelectHandler()"
x-htmldialog="open = false"
closeby="any"
x-show="open"
x-transition
@toggle-product-select.window="initializeModal($event.detail)">
<!-- Header -->
<div class="p-4 border-b flex items-center justify-between">
<h2 class="text-xl font-semibold"><?= $escaper->escapeHtml(__('Select Products')) ?></h2>
<button type="button" @click="open = false" class="text-gray-500 hover:text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
</button>
</div>
<!-- Search and filters -->
<div class="p-4 border-b">
<input type="text"
x-model="searchTerm"
@input.debounce.300ms="searchProducts()"
placeholder="Search products..."
class="w-full px-4 py-2 border rounded-md">
</div>
<!-- Product grid -->
<div class="flex-1 overflow-y-auto p-4">
<div class="grid grid-cols-3 gap-4">
<template x-for="product in availableProducts" :key="product.id">
<div class="border rounded-lg p-4 cursor-pointer hover:border-blue-500"
:class="{ 'border-blue-500 bg-blue-50': isSelected(product.id) }"
@click="toggleProduct(product)">
<img :src="product.image"
:alt="product.name"
class="w-full h-32 object-cover rounded mb-2">
<h3 class="font-medium text-sm" x-text="product.name"></h3>
<p class="text-xs text-gray-500" x-text="product.sku"></p>
</div>
</template>
</div>
<div x-show="availableProducts.length === 0" class="text-center py-8 text-gray-500">
<?= $escaper->escapeHtml(__('No products found')) ?>
</div>
</div>
<!-- Footer -->
<div class="p-4 border-t flex items-center justify-between">
<div class="text-sm text-gray-600">
<span x-text="selectedProducts.length"></span> /
<span x-text="maxProducts"></span> selected
</div>
<div class="flex gap-4">
<button type="button"
class="btn"
@click="open = false">
<?= $escaper->escapeHtml(__('Cancel')) ?>
</button>
<button type="button"
class="btn btn-primary"
@click="saveProducts()">
<?= $escaper->escapeHtml(__('Save Selection')) ?>
</button>
</div>
</div>
</dialog>
<script>
function initProductSelectHandler() {
return {
open: false,
uid: null,
fieldName: null,
maxProducts: 10,
searchTerm: '',
selectedProducts: [],
availableProducts: [],
// Initialize modal when field template dispatches event
initializeModal({ isOpen, uid, fieldName, fieldValue, maxProducts } = {}) {
this.uid = uid;
this.fieldName = fieldName;
this.maxProducts = maxProducts || 10;
// Parse current selection
try {
this.selectedProducts = JSON.parse(fieldValue || '[]');
} catch (e) {
this.selectedProducts = [];
}
// Load products
this.searchProducts();
// Open modal
this.open = isOpen;
},
// Search/load products (mock implementation - replace with real API call)
async searchProducts() {
// In real implementation, fetch from Magento API:
// const response = await fetch(`/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=name&searchCriteria[filterGroups][0][filters][0][value]=${this.searchTerm}`);
// Mock data for demonstration
this.availableProducts = [
{ id: 1, name: 'Product 1', sku: 'SKU001', image: 'https://via.placeholder.com/150' },
{ id: 2, name: 'Product 2', sku: 'SKU002', image: 'https://via.placeholder.com/150' },
{ id: 3, name: 'Product 3', sku: 'SKU003', image: 'https://via.placeholder.com/150' },
].filter(p => p.name.toLowerCase().includes(this.searchTerm.toLowerCase()));
},
// Check if product is selected
isSelected(productId) {
return this.selectedProducts.some(p => p.id === productId);
},
// Toggle product selection
toggleProduct(product) {
const index = this.selectedProducts.findIndex(p => p.id === product.id);
if (index >= 0) {
// Remove product
this.selectedProducts.splice(index, 1);
} else if (this.selectedProducts.length < this.maxProducts) {
// Add product
this.selectedProducts.push(product);
}
},
// Save selection and dispatch editor-change event
saveProducts() {
// Dispatch event to update field value
this.$dispatch('editor-change', {
name: this.uid, // IMPORTANT: use 'name' not 'uid'
field: this.fieldName, // IMPORTANT: use 'field' not 'fieldName'
value: this.selectedProducts,
saveState: true
});
this.open = false;
}
}
}
</script>Step 3: Register Field Type
<!-- etc/adminhtml/di.xml -->
<type name="Hyva\CmsLiveviewEditor\Model\CustomField">
<arguments>
<argument name="customTypes" xsi:type="array">
<item name="product_selector" xsi:type="string">
Vendor_Module::field-types/product-selector.phtml
</item>
</argument>
</arguments>
</type>Step 4: Register Handler Modal
<!-- view/adminhtml/layout/liveview_editor.xml -->
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="before.body.end">
<block name="product_selector_handler"
template="Vendor_Module::handlers/product-selector-handler.phtml"/>
</referenceContainer>
</body>
</page>Usage in components.json:
{
"product_showcase": {
"label": "Product Showcase",
"content": {
"featured_products": {
"type": "custom_type",
"custom_type": "product_selector",
"label": "Featured Products",
"attributes": {
"max_products": 6,
"required": true
}
}
}
}
}Pattern Comparison
| Aspect | Basic Field | Inline Handler | Modal Handler |
|---|---|---|---|
| Template Files | 1 (field) | 1 (field) | 2 (field + modal) |
| Layout XML | No | No | Yes |
| Alpine.js | Optional | Yes | Yes |
| Event Communication | No | No | Yes |
| UI Complexity | Low | Medium | High |
| Screen Space | Field area | Field area + dropdown | Full modal |
| Best For | Validation, simple inputs | Enhanced dropdowns, pickers | Complex selection, galleries |
Choosing the Right Pattern
1. Start simple: Can you use Pattern A (basic field)? If yes, use it. 2. Need enhancement?: Does it fit inline (Pattern B)? Use inline handler. 3. Need space?: Use Pattern C (modal handler) only when necessary.
The more complex patterns require more code and maintenance, so always use the simplest pattern that meets your needs.
Custom Field Type Template Requirements
This document describes the required markup patterns and elements for custom field type templates in Hyvä CMS.
Required Template Structure
Every custom field type template must include specific elements and follow naming patterns to integrate properly with the Hyvä CMS editor's validation, preview updates, and error handling.
Template Variables
All custom field type templates receive these variables from the CMS editor:
// Component and field identifiers
$uid = (string) $block->getData('uid'); // Component unique ID
$fieldName = (string) $block->getData('name'); // Field name from components.json
$fieldValue = $block->getData('value') ?? ''; // Current field value (use ?? for null safety)
// Field configuration
$options = (array) $block->getData('options'); // Options array (for select-like fields)
$attributes = (array) $block->getData('attributes') ?? []; // HTML attributes from components.json
// Validation state
$hasError = isset($magewire->errors[$uid][$fieldName]); // Does field have validation error?
$errorMessage = $hasError ? $magewire->errors[$uid][$fieldName] : ''; // Error message textRequired Template Elements
1. Field Container Element
The root element must be a div with class field-container and a specific ID format:
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>Requirements:
- ID format: Must be exactly
field-container-{uid}_{fieldName} - data-error attribute: Must be present when
$hasErroris true - Both are required for validation highlighting and error styling
2. Input Element Name Attribute
All input elements must have a name attribute following this pattern:
<input type="text"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>">Requirements:
- Name format: Must be exactly
{uid}_{fieldName} - Required for:
- Frontend HTML5 validation
- Editor's click-to-focus feature (clicking field value in preview focuses the input)
3. Validation Messages Container
Include an element to display validation error messages:
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none">
<?php if ($hasError): ?>
<li class="error-message text-red-600 text-sm mt-1">
<?= $escaper->escapeHtml($errorMessage) ?>
</li>
<?php endif; ?>
</ul>Requirements:
- ID format: Must be exactly
validation-messages-{uid}_{fieldName} - Hyvä CMS injects error messages into this container
Custom validation message location:
If you need validation messages elsewhere in the template, add a data-validation-messages-selector attribute to the field container:
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
data-validation-messages-selector="#my-custom-error-location"
<?= $hasError ? 'data-error' : '' ?>>Then create the custom location with any ID or class you want:
<div id="my-custom-error-location" class="validation-messages"></div>4. Field Value Update Methods
Hyvä CMS provides two Alpine.js methods for updating field values:
updateWireField (Recommended Default)
<input type="text"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)">Behavior:
- Updates preview immediately
- Sends value to server via Magewire
- Triggers server-side validation on every change
- Keeps component state synchronized
Use when: Default choice for most fields
updateField (Specialized Use)
<input type="text"
@input="updateField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)">Behavior:
- Updates preview immediately via AJAX
- Does NOT send to server until save
- Stores value in local state
- No server-side validation until save
Use when: Implementing debounced inputs or need to minimize server requests for performance
Important Limitation
If you add custom Alpine.js components to your field template, you CANNOT set field values through updateField or updateWireField from within your Alpine component.
Solution: Keep input fields outside your Alpine component and update them with vanilla JavaScript:
<div x-data="myCustomComponent()">
<!-- Your Alpine component UI -->
<button @click="selectValue('foo')">Select Foo</button>
</div>
<!-- Input OUTSIDE the Alpine component -->
<input type="hidden"
id="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>">
<script>
function myCustomComponent() {
return {
selectValue(value) {
// Update the input with vanilla JS
const input = document.getElementById('<?= $escaper->escapeJs("{$uid}_{$fieldName}") ?>');
input.value = value;
input.dispatchEvent(new Event('change', { bubbles: true }));
}
}
}
</script>Field Attributes and HTML5 Validation
The FieldTypes view model provides a method to filter component configuration attributes:
use Hyva\CmsLiveviewEditor\ViewModel\Adminhtml\FieldTypes;
/** @var FieldTypes $fieldTypes */
$fieldTypes = $viewModels->require(FieldTypes::class);
$attributes = (array) $block->getData('attributes') ?? [];
$filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes);What gets filtered:
- Keeps:
pattern,required,minlength,maxlength,min,max,step, etc. - Removes:
class,comment, and other non-validation attributes
Apply to input elements:
<input type="text"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?php foreach ($filteredAttributes as $attr => $attrValue): ?>
<?= $escaper->escapeHtmlAttr($attr) ?>="<?= $escaper->escapeHtmlAttr($attrValue) ?>"
<?php endforeach; ?>>Hyvä CMS automatically validates custom field types against HTML5 validation attributes.
Complete Template Example
Here's a complete basic custom field type template with all required elements:
<?php
declare(strict_types=1);
use Magento\Backend\Block\Template;
use Magento\Framework\Escaper;
use Hyva\CmsLiveviewEditor\Magewire\LiveviewComposer;
use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\CmsLiveviewEditor\ViewModel\Adminhtml\FieldTypes;
/** @var Template $block */
/** @var Escaper $escaper */
/** @var LiveviewComposer $magewire */
/** @var ViewModelRegistry $viewModels */
/** @var FieldTypes $fieldTypes */
$fieldTypes = $viewModels->require(FieldTypes::class);
// Component and field identifiers
$uid = (string) $block->getData('uid');
$fieldName = (string) $block->getData('name');
$fieldValue = $block->getData('value') ?? '';
// HTML attributes and validation
$attributes = (array) $block->getData('attributes') ?? [];
$filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes);
// Validation state
$hasError = isset($magewire->errors[$uid][$fieldName]);
$errorMessage = $hasError ? $magewire->errors[$uid][$fieldName] : '';
?>
<div class="field-container"
id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
<?= $hasError ? 'data-error' : '' ?>>
<input type="text"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($fieldValue) ?>"
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)"
class="form-input <?= $hasError ? 'error field-error' : '' ?>"
<?php foreach ($filteredAttributes as $attr => $attrValue): ?>
<?= $escaper->escapeHtmlAttr($attr) ?>="<?= $escaper->escapeHtmlAttr($attrValue) ?>"
<?php endforeach; ?>>
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
class="validation-messages list-none">
<?php if ($hasError): ?>
<li class="error-message text-red-600 text-sm mt-1">
<?= $escaper->escapeHtml($errorMessage) ?>
</li>
<?php endif; ?>
</ul>
</div>Common Patterns
Radio Button Group
<div class="field-container" id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>" <?= $hasError ? 'data-error' : '' ?>>
<div class="radio-group flex gap-4">
<?php foreach ($options as $option): ?>
<label class="inline-flex items-center">
<input type="radio"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
value="<?= $escaper->escapeHtmlAttr($option['value']) ?>"
<?= $option['value'] === $fieldValue ? 'checked' : '' ?>
@change="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
$event.target.value
)"
class="form-radio <?= $hasError ? 'error field-error' : '' ?>">
<span class="ml-2"><?= $escaper->escapeHtml($option['label']) ?></span>
</label>
<?php endforeach; ?>
</div>
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>" class="validation-messages list-none"></ul>
</div>Checkbox Group (Multiple Values)
<?php
$selectedValues = $fieldValue ? explode(',', $fieldValue) : [];
?>
<div class="field-container" id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>" <?= $hasError ? 'data-error' : '' ?>>
<div class="checkbox-group flex flex-col gap-2" x-data="{ selected: <?= $escaper->escapeHtmlAttr(json_encode($selectedValues)) ?> }">
<?php foreach ($options as $option): ?>
<label class="inline-flex items-center">
<input type="checkbox"
value="<?= $escaper->escapeHtmlAttr($option['value']) ?>"
:checked="selected.includes('<?= $escaper->escapeJs($option['value']) ?>')"
@change="
if ($event.target.checked) {
selected.push('<?= $escaper->escapeJs($option['value']) ?>');
} else {
selected = selected.filter(v => v !== '<?= $escaper->escapeJs($option['value']) ?>');
}
updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
selected.join(',')
);
"
class="form-checkbox">
<span class="ml-2"><?= $escaper->escapeHtml($option['label']) ?></span>
</label>
<?php endforeach; ?>
</div>
<input type="hidden" name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>">
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>" class="validation-messages list-none"></ul>
</div>Range Slider with Live Value Display
<div class="field-container" id="field-container-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>" <?= $hasError ? 'data-error' : '' ?>>
<div x-data="{ value: '<?= $escaper->escapeJs($fieldValue ?: '50') ?>' }">
<input type="range"
name="<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>"
x-model="value"
@input="updateWireField(
'<?= $escaper->escapeHtmlAttr($uid) ?>',
'<?= $escaper->escapeHtmlAttr($fieldName) ?>',
value
)"
min="0" max="100" step="1"
class="w-full">
<div class="text-center mt-2">
<span x-text="value"></span>
</div>
</div>
<ul id="validation-messages-<?= $escaper->escapeHtmlAttr("{$uid}_{$fieldName}") ?>" class="validation-messages list-none"></ul>
</div>Error State Styling
The CMS editor automatically applies error styling when the data-error attribute is present on the field container and the input has the error field-error classes.
Custom error styling can be added in your module's admin CSS if needed.
Testing Checklist
When implementing a custom field type template, verify:
- [ ] Field container has correct ID format:
field-container-{uid}_{fieldName} - [ ] Input has correct name format:
{uid}_{fieldName} - [ ] Validation messages container has correct ID format:
validation-messages-{uid}_{fieldName} - [ ] Field container has
data-errorattribute when$hasErroris true - [ ] Field value updates on change using
updateWireFieldorupdateField - [ ] HTML5 validation attributes are applied via
$filteredAttributes - [ ] Clicking field value in preview focuses the input
- [ ] Validation errors display in the validation messages container
- [ ] Field value persists after save and refresh
Related skills
How it compares
Pick hyva-cms-custom-field for Hyvä-on-Magento CMS extensions; pick generic Magento module skills when the theme is Luma or admin-only backend work is required.
FAQ
What does hyva-cms-custom-field help developers build?
hyva-cms-custom-field guides adding Hyvä CMS custom fields in Magento so merchants can manage extra content blocks, metadata, and merchandising data, then rendering those values in Hyvä storefront templates.
Which storefront stack does hyva-cms-custom-field target?
hyva-cms-custom-field targets Magento shops using Hyvä Theme and Hyvä CMS, focusing on admin field definitions and frontend template output rather than unrelated PHP frameworks.