hyva-cms-custom-field

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hyvä CMS Custom Field Type Creator

Hyvä CMS 自定义字段类型创建指南

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.
本技能指导您为Hyvä CMS组件创建自定义字段类型和字段处理器。自定义字段类型通过为CMS编辑器界面提供专用输入控件,扩展了内置字段类型(文本、文本域、选择框等)。
两种自定义字段类型:
  1. 基础自定义字段类型:支持直接数据输入的自定义输入控件(例如日期范围选择器、颜色选择器、自定义验证)
  2. 字段处理器:具有复杂交互的增强型UI(例如带图片的产品选择器、可搜索下拉框、链接配置模态框)
命令执行:对于需要在开发环境中运行的命令(例如
bin/magento
),请使用
hyva-exec-shell-cmd
技能检测环境并确定合适的命令包装器。

Workflow

工作流程

Step 1: Module Selection

步骤1:模块选择

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_CmsBase
    and
    Hyva_CmsLiveviewEditor
    in
    etc/module.xml
  • hyva-themes/commerce-module-cms
    in
    composer.json
Add missing dependencies if needed.
如果提示中未指定,请确定自定义字段类型的创建位置:
选项A:新建模块
使用
hyva-create-module
技能,配置:
  • dependencies
    :
    ["Hyva_CmsBase", "Hyva_CmsLiveviewEditor"]
  • composer_require
    :
    {"hyva-themes/commerce-module-cms": "^1.0"}
选项B:现有模块
验证模块是否包含所需依赖:
  • etc/module.xml
    中是否存在
    Hyva_CmsBase
    Hyva_CmsLiveviewEditor
  • composer.json
    中是否存在
    hyva-themes/commerce-module-cms
如有需要,添加缺失的依赖。

Step 2: Field Type Details

步骤2:字段类型详情收集

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?)
收集自定义字段类型的相关信息:
  1. 字段类型名称(小写标识符,例如
    date_range
    product_selector
    color_picker
  2. 用途(该字段用于收集什么数据?)
  3. UI模式
    • 基础字段:带验证的简单输入(日期选择器、格式输入框、增强型文本字段)
    • 内联处理器:字段区域内的增强型控件(可搜索下拉框、带色板的颜色选择器)
    • 模态处理器:需要更多空间的复杂选择界面(产品选择器、链接配置器、媒体库)
  4. 数据结构(简单字符串、JSON对象、数组?)
  5. 验证要求(格式、必填、自定义规则?)

Step 3: Implementation Pattern Selection

步骤3:选择实现模式

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.
根据步骤2中确定的UI模式选择对应的实现方案:
模式A:基础自定义字段类型
适用于带自定义HTML5验证或专用输入控件的简单输入:
  • 仅需单个字段模板文件
  • 无需独立的处理器模态框
  • 示例:日期范围选择器、自定义格式验证、滑块输入
模式B:内联字段处理器
适用于保留在字段区域内的增强型控件:
  • 带Alpine.js组件的单个模板文件
  • 无需独立的处理器模态框
  • 示例:可搜索选择下拉框、带色板的颜色选择器
模式C:基于模态框的字段处理器
适用于需要更多空间的复杂选择界面:
  • 字段模板(显示选择结果 + 触发按钮)
  • 处理器模态框模板(独立的对话框,包含完整UI)
  • 用于注册处理器的布局XML
  • 示例:产品选择器、链接配置、媒体库
查看
references/handler-patterns.md
获取每种类型的详细实现模式和代码示例。

Step 4: Generate Field Template

步骤4:生成字段模板

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 type
  • inline-handler.phtml.tpl
    - Inline enhanced control
  • modal-field.phtml.tpl
    - Modal handler field template
See
references/template-requirements.md
for detailed template requirements and patterns.
view/adminhtml/templates/field-types/[field-type-name].phtml
路径下创建字段模板。
模板必需元素:
  1. 带正确ID的字段容器:
    field-container-{uid}_{fieldName}
  2. 带名称的输入元素:
    {uid}_{fieldName}
  3. 验证消息容器:
    validation-messages-{uid}_{fieldName}
  4. 值变更时调用
    updateWireField()
    updateField()
  5. 通过
    $magewire->errors
    处理错误状态
  6. 重要提示:使用空值合并运算符处理字段值:
    $block->getData('value') ?? ''
    (请勿使用类型转换)
assets/templates/
中选择合适的模板:
  • basic-field.phtml.tpl
    - 基础自定义字段类型
  • inline-handler.phtml.tpl
    - 内联增强型控件
  • modal-field.phtml.tpl
    - 模态处理器字段模板
查看
references/template-requirements.md
获取详细的模板要求和模式。

Step 5: Generate Handler Modal (if needed)

步骤5:生成处理器模态框(如需要)

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.
仅针对基于模态框的处理器,在
view/adminhtml/templates/handlers/[handler-name]-handler.phtml
路径下创建处理器模板。
处理器模态框结构:
  1. 带Alpine.js组件和
    open:flex
    类的
    <dialog>
    元素(请勿使用静态
    flex
    类)
  2. 监听来自字段模板的初始化事件
  3. 实现选择UI(搜索、筛选、网格等)
  4. 保存时触发
    editor-change
    事件
assets/templates/modal-handler.phtml.tpl
为起点进行创建。
查看
references/handler-communication.md
获取事件协议和数据交换模式。

Step 6: Register Field Type

步骤6:注册字段类型

Add registration to
etc/adminhtml/di.xml
:
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>
etc/adminhtml/di.xml
中添加注册配置:
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)

步骤7:注册处理器模态框(如需要)

For modal-based handlers only, create or update
view/adminhtml/layout/liveview_editor.xml
:
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.
仅针对基于模态框的处理器,创建或更新
view/adminhtml/layout/liveview_editor.xml
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>
注意:内联处理器无需布局XML注册。

Step 8: Usage Example

步骤8:使用示例

Provide an example of using the custom field type in
components.json
:
json
{
    "my_component": {
        "label": "My Component",
        "content": {
            "[field_name]": {
                "type": "custom_type",
                "custom_type": "[field_type_name]",
                "label": "Field Label",
                "attributes": {
                    "required": true,
                    "pattern": ".*"
                }
            }
        }
    }
}
提供在
components.json
中使用自定义字段类型的示例:
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

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 (
    updateWireField
    vs
    updateField
    )
  • HTML5 validation attributes
  • Error state handling
Read this file when implementing the field template to ensure proper integration with the CMS editor.
自定义字段类型模板要求的完整参考:
  • 必需的标记模式和元素ID
  • 字段容器结构
  • 验证消息容器
  • 字段值更新方法(
    updateWireField
    vs
    updateField
  • HTML5验证属性
  • 错误状态处理
实现字段模板时请阅读此文件,确保与CMS编辑器正确集成。

references/handler-patterns.md

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.
三种自定义字段类型的实现模式:
  • 基础自定义字段类型(简单输入)
  • 内联字段处理器(增强型控件)
  • 基于模态框的字段处理器(对话框选择)
每种模式包含:
  • 完整代码示例
  • 适用场景
  • Alpine.js组件结构
  • 数据流和状态管理
选择实现模式和编写模板代码时请阅读此文件。

references/handler-communication.md

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

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.
Hyvä CMS内置字段处理器参考:
  • 产品处理器(基于模态框,图片网格选择)
  • 链接处理器(基于模态框,多类型链接配置)
  • 可搜索选择器(内联增强型下拉框)
每种处理器包含:
  • 在Hyvä CMS模块中的位置
  • 关键特性和模式
  • 使用示例
  • 可供参考的代码
寻找实现示例或可复用模式时请阅读此文件。

assets/templates/basic-field.phtml.tpl

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)
适用于带自定义验证或输入控件的基础自定义字段类型模板。
占位符:
  • {{FIELD_TYPE_NAME}}
    - 自定义字段类型标识符
  • {{FIELD_INPUTS}}
    - 输入元素HTML
  • {{VALIDATION_LOGIC}}
    - 自定义验证JavaScript(可选)

assets/templates/inline-handler.phtml.tpl

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
适用于内联增强型控件(可搜索下拉框、颜色选择器等)的模板。
占位符:
  • {{HANDLER_NAME}}
    - Alpine.js组件名称
  • {{HANDLER_LOGIC}}
    - Alpine.js组件实现代码
  • {{HANDLER_UI}}
    - 增强型控件HTML

assets/templates/modal-field.phtml.tpl

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
适用于基于模态框的处理器的字段模板(触发按钮 + 隐藏输入框)。
占位符:
  • {{EVENT_NAME}}
    - 要触发的自定义事件名称
  • {{BUTTON_LABEL}}
    - 按钮文本
  • {{DISPLAY_VALUE}}
    - 当前选择结果的显示内容

assets/templates/modal-handler.phtml.tpl

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
适用于基于模态框的选择界面的处理器模态框模板。
占位符:
  • {{HANDLER_NAME}}
    - Alpine.js组件名称
  • {{MODAL_TITLE}}
    - 对话框标题文本
  • {{SELECTION_UI}}
    - 选择界面HTML
  • {{SAVE_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
  1. 模板要求:所有自定义字段类型必须遵循必需的标记模式(容器ID、输入名称、验证消息)
  2. 处理器注册:模态框处理器需要布局XML注册;内联处理器不需要
  3. 验证:通过
    $filteredAttributes
    应用HTML5验证属性以实现自动验证
  4. Alpine组件:如果使用自定义Alpine.js组件,请将输入字段放在组件外部,并通过原生JS更新
  5. 内置示例:参考
    Hyva_CmsLiveviewEditor::page/js/
    中的内置处理器,使用经过验证的模式

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
    php
    // 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
    php
    <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
    php
    /** @var Icons $icons */
    $icons = $viewModels->require(Icons::class);
    <?= /** @noEscape */ $icons->trashHtml('', 22, 22) ?>
  8. FieldTypes View Model: Use for attribute filtering
    php
    /** @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.end
      container 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 is
    null
    , 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.phtml
    which use
    ?? []
    pattern
  1. 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.phtml
    which use
    open:flex flex-col
  1. 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:
    php
    $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
    value
    attribute without JSON-encoding first
<!-- Copyright © Hyvä Themes https://hyva.io. All rights reserved. Licensed under OSL 3.0 -->
基于Hyvä CMS内置处理器的实现:
  1. 事件命名规范:使用
    toggle-{type}-select
    模式
    • ✅ 正确示例:
      toggle-product-select
      ,
      toggle-link-select
      ,
      toggle-category-select
    • ❌ 错误示例:
      toggle-product-handler
      ,
      toggle-link-handler
  2. 处理器函数命名:使用
    init{Type}Select()
    模式
    • ✅ 示例:
      initProductSelect()
      ,
      initLinkSelect()
      ,
      initCategorySelect()
  3. 字段值更新方法
    • 优先使用
      updateWireField
      (默认):产品、链接、分类处理器
      • 通过Magewire触发即时服务器端验证
      • 保持组件状态同步
    • 使用
      updateField
      (特殊场景):图片处理器、防抖输入(颜色、范围)
      • 无需服务器往返即可更新预览
      • 延迟验证直到保存时
  4. JSON编码模式:所有复杂数据(数组、对象)必须进行JSON编码
    php
    // 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 兼容Livewire:可搜索选择器使用
    wire:ignore
    包装器
    php
    <div wire:ignore>
        <div x-data="initSearchableSelect(...)">
            <!-- Alpine component -->
        </div>
    </div>
  6. 独立处理器文件:即使是内联处理器也可能有独立的函数文件
    • 字段模板:
      liveview/field-types/searchable_select.phtml
    • 处理器函数:
      page/js/searchable-select-handler.phtml
  7. Icons 视图模型:用于UI元素
    php
    /** @var Icons $icons */
    $icons = $viewModels->require(Icons::class);
    <?= /** @noEscape */ $icons->trashHtml('', 22, 22) ?>
  8. FieldTypes 视图模型:用于属性过滤
    php
    /** @var FieldTypes $fieldTypes */
    $fieldTypes = $viewModels->require(FieldTypes::class);
    $filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes);
    // Or for specific attributes:
    $filteredAttributes = $fieldTypes->getAttributesByKeys($attributes, ['required', 'data-required']);
  9. 关键注意:布局XML referenceContainer:处理器模态框必须使用
    before.body.end
    容器
    • ✅ 正确:
      <referenceContainer name="before.body.end">
    • ❌ 错误:
      <referenceContainer name="content">
    • before.body.end
      容器确保处理器模态框加载在页面body末尾,这是Alpine.js正确初始化和模态框功能正常的必要条件
  10. 关键注意:字段值类型处理:切勿对字段值使用类型转换,始终使用空值合并运算符
    • ✅ 正确:
      $fieldValue = $block->getData('value') ?? '';
    • ❌ 错误:
      $fieldValue = (string) $block->getData('value');
    • 类型转换
      (string)
      在值为
      null
      时会失败,导致PHP错误
    • 对于字符串值使用
      ?? ''
      ,数组值使用
      ?? []
      ,或对应数据类型的合适默认值
    • 参考:类似
      category.phtml
      的内置字段类型使用
      ?? []
      模式
  11. 关键注意:对话框模态框类:处理器模态框必须使用
    open:flex
    而非静态
    flex
    • ✅ 正确:
      <dialog class="... open:flex flex-col">
    • ❌ 错误:
      <dialog class="... flex flex-col">
      (模态框始终可见)
    • open:
      前缀仅在对话框打开时应用样式(原生HTML对话框状态)
    • 参考:类似
      category-handler.phtml
      的内置处理器使用
      open:flex flex-col
  12. 关键注意:复杂数据类型处理:对于存储JSON/数组数据的字段,需同时处理数组和字符串类型
    • 字段值可能以已解码的数组形式返回,也可能以JSON字符串形式返回(取决于存储/上下文)
    • ✅ 正确模式:
      php
      $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;
    • ❌ 错误:未进行类型检查就使用
      json_decode($fieldValue)
      (如果值已经是数组则会失败)
    • ❌ 错误:直接将数组用于
      value
      属性而不先进行JSON编码
<!-- Copyright © Hyvä Themes https://hyva.io. All rights reserved. Licensed under OSL 3.0 -->