hyva-cms-custom-field
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHyvä 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:
- Basic Custom Field Type: Custom input control with direct data entry (e.g., date range, color picker, custom validation)
- 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., ), use the skill to detect the environment and determine the appropriate command wrapper.
bin/magentohyva-exec-shell-cmd本技能指导您为Hyvä CMS组件创建自定义字段类型和字段处理器。自定义字段类型通过为CMS编辑器界面提供专用输入控件,扩展了内置字段类型(文本、文本域、选择框等)。
两种自定义字段类型:
- 基础自定义字段类型:支持直接数据输入的自定义输入控件(例如日期范围选择器、颜色选择器、自定义验证)
- 字段处理器:具有复杂交互的增强型UI(例如带图片的产品选择器、可搜索下拉框、链接配置模态框)
命令执行:对于需要在开发环境中运行的命令(例如),请使用技能检测环境并确定合适的命令包装器。
bin/magentohyva-exec-shell-cmdWorkflow
工作流程
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 skill with:
hyva-create-module- :
dependencies["Hyva_CmsBase", "Hyva_CmsLiveviewEditor"] - :
composer_require{"hyva-themes/commerce-module-cms": "^1.0"}
Option B: Existing Module
Verify the module has required dependencies:
- and
Hyva_CmsBaseinHyva_CmsLiveviewEditoretc/module.xml - in
hyva-themes/commerce-module-cmscomposer.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_CmsBaseHyva_CmsLiveviewEditor - 中是否存在
composer.jsonhyva-themes/commerce-module-cms
如有需要,添加缺失的依赖。
Step 2: Field Type Details
步骤2:字段类型详情收集
Gather information about the custom field type:
- Field type name (lowercase identifier, e.g., ,
date_range,product_selector)color_picker - Purpose (what data does it collect?)
- 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)
- Data structure (simple string, JSON object, array?)
- Validation requirements (pattern, required, custom rules?)
收集自定义字段类型的相关信息:
- 字段类型名称(小写标识符,例如、
date_range、product_selector)color_picker - 用途(该字段用于收集什么数据?)
- UI模式:
- 基础字段:带验证的简单输入(日期选择器、格式输入框、增强型文本字段)
- 内联处理器:字段区域内的增强型控件(可搜索下拉框、带色板的颜色选择器)
- 模态处理器:需要更多空间的复杂选择界面(产品选择器、链接配置器、媒体库)
- 数据结构(简单字符串、JSON对象、数组?)
- 验证要求(格式、必填、自定义规则?)
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 for detailed implementation patterns and code examples for each type.
references/handler-patterns.md根据步骤2中确定的UI模式选择对应的实现方案:
模式A:基础自定义字段类型
适用于带自定义HTML5验证或专用输入控件的简单输入:
- 仅需单个字段模板文件
- 无需独立的处理器模态框
- 示例:日期范围选择器、自定义格式验证、滑块输入
模式B:内联字段处理器
适用于保留在字段区域内的增强型控件:
- 带Alpine.js组件的单个模板文件
- 无需独立的处理器模态框
- 示例:可搜索选择下拉框、带色板的颜色选择器
模式C:基于模态框的字段处理器
适用于需要更多空间的复杂选择界面:
- 字段模板(显示选择结果 + 触发按钮)
- 处理器模态框模板(独立的对话框,包含完整UI)
- 用于注册处理器的布局XML
- 示例:产品选择器、链接配置、媒体库
查看获取每种类型的详细实现模式和代码示例。
references/handler-patterns.mdStep 4: Generate Field Template
步骤4:生成字段模板
Create the field template at .
view/adminhtml/templates/field-types/[field-type-name].phtmlRequired template elements:
- Field container with proper ID:
field-container-{uid}_{fieldName} - Input element(s) with name:
{uid}_{fieldName} - Validation messages container:
validation-messages-{uid}_{fieldName} - or
updateWireField()call on value changeupdateField() - Error state handling via
$magewire->errors - IMPORTANT: Use null coalescing for field value: (NOT type casting)
$block->getData('value') ?? ''
Use the appropriate template from :
assets/templates/- - Basic custom field type
basic-field.phtml.tpl - - Inline enhanced control
inline-handler.phtml.tpl - - Modal handler field template
modal-field.phtml.tpl
See for detailed template requirements and patterns.
references/template-requirements.md在路径下创建字段模板。
view/adminhtml/templates/field-types/[field-type-name].phtml模板必需元素:
- 带正确ID的字段容器:
field-container-{uid}_{fieldName} - 带名称的输入元素:
{uid}_{fieldName} - 验证消息容器:
validation-messages-{uid}_{fieldName} - 值变更时调用或
updateWireField()updateField() - 通过处理错误状态
$magewire->errors - 重要提示:使用空值合并运算符处理字段值:(请勿使用类型转换)
$block->getData('value') ?? ''
从中选择合适的模板:
assets/templates/- - 基础自定义字段类型
basic-field.phtml.tpl - - 内联增强型控件
inline-handler.phtml.tpl - - 模态处理器字段模板
modal-field.phtml.tpl
查看获取详细的模板要求和模式。
references/template-requirements.mdStep 5: Generate Handler Modal (if needed)
步骤5:生成处理器模态框(如需要)
For modal-based handlers only, create the handler template at .
view/adminhtml/templates/handlers/[handler-name]-handler.phtmlHandler modal structure:
- element with Alpine.js component and
<dialog>class (NOT staticopen:flex)flex - Listen for initialization event from field template
- Implement selection UI (search, filters, grid, etc.)
- Dispatch event on save
editor-change
Use as the starting point.
assets/templates/modal-handler.phtml.tplSee for event protocols and data exchange patterns.
references/handler-communication.md仅针对基于模态框的处理器,在路径下创建处理器模板。
view/adminhtml/templates/handlers/[handler-name]-handler.phtml处理器模态框结构:
- 带Alpine.js组件和类的
open:flex元素(请勿使用静态<dialog>类)flex - 监听来自字段模板的初始化事件
- 实现选择UI(搜索、筛选、网格等)
- 保存时触发事件
editor-change
以为起点进行创建。
assets/templates/modal-handler.phtml.tpl查看获取事件协议和数据交换模式。
references/handler-communication.mdStep 6: Register Field Type
步骤6:注册字段类型
Add registration to :
etc/adminhtml/di.xmlxml
<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.xmlxml
<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.xmlxml
<?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.xmlxml
<?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.jsonjson
{
"my_component": {
"label": "My Component",
"content": {
"[field_name]": {
"type": "custom_type",
"custom_type": "[field_type_name]",
"label": "Field Label",
"attributes": {
"required": true,
"pattern": ".*"
}
}
}
}
}提供在中使用自定义字段类型的示例:
components.jsonjson
{
"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 (vs
updateWireField)updateField - HTML5 validation attributes
- Error state handling
Read this file when implementing the field template to ensure proper integration with the CMS editor.
自定义字段类型模板要求的完整参考:
- 必需的标记模式和元素ID
- 字段容器结构
- 验证消息容器
- 字段值更新方法(vs
updateWireField)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:
- - Custom field type identifier
{{FIELD_TYPE_NAME}} - - Input element(s) HTML
{{FIELD_INPUTS}} - - Custom validation JavaScript (optional)
{{VALIDATION_LOGIC}}
适用于带自定义验证或输入控件的基础自定义字段类型模板。
占位符:
- - 自定义字段类型标识符
{{FIELD_TYPE_NAME}} - - 输入元素HTML
{{FIELD_INPUTS}} - - 自定义验证JavaScript(可选)
{{VALIDATION_LOGIC}}
assets/templates/inline-handler.phtml.tpl
assets/templates/inline-handler.phtml.tpl
Template for inline enhanced controls (searchable dropdown, color picker, etc.).
Placeholders:
- - Alpine.js component name
{{HANDLER_NAME}} - - Alpine.js component implementation
{{HANDLER_LOGIC}} - - Enhanced control HTML
{{HANDLER_UI}}
适用于内联增强型控件(可搜索下拉框、颜色选择器等)的模板。
占位符:
- - Alpine.js组件名称
{{HANDLER_NAME}} - - Alpine.js组件实现代码
{{HANDLER_LOGIC}} - - 增强型控件HTML
{{HANDLER_UI}}
assets/templates/modal-field.phtml.tpl
assets/templates/modal-field.phtml.tpl
Field template for modal-based handlers (trigger button + hidden input).
Placeholders:
- - Custom event name to dispatch
{{EVENT_NAME}} - - Button text
{{BUTTON_LABEL}} - - Current selection display
{{DISPLAY_VALUE}}
适用于基于模态框的处理器的字段模板(触发按钮 + 隐藏输入框)。
占位符:
- - 要触发的自定义事件名称
{{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:
- - Alpine.js component name
{{HANDLER_NAME}} - - Dialog header text
{{MODAL_TITLE}} - - Selection interface HTML
{{SELECTION_UI}} - - Save button logic
{{SAVE_LOGIC}}
适用于基于模态框的选择界面的处理器模态框模板。
占位符:
- - Alpine.js组件名称
{{HANDLER_NAME}} - - 对话框标题文本
{{MODAL_TITLE}} - - 选择界面HTML
{{SELECTION_UI}} - - 保存按钮逻辑
{{SAVE_LOGIC}}
Important Guidelines
重要指南
Core Requirements
核心要求
- Template Requirements: All custom field types must follow required markup patterns (container ID, input name, validation messages)
- Handler Registration: Modal handlers need layout XML registration; inline handlers do not
- Validation: Apply HTML5 validation attributes via for automatic validation
$filteredAttributes - Alpine Components: If using custom Alpine components, keep input fields outside the component and update via vanilla JS
- Built-In Examples: Reference built-in handlers in for proven patterns
Hyva_CmsLiveviewEditor::page/js/
- 模板要求:所有自定义字段类型必须遵循必需的标记模式(容器ID、输入名称、验证消息)
- 处理器注册:模态框处理器需要布局XML注册;内联处理器不需要
- 验证:通过应用HTML5验证属性以实现自动验证
$filteredAttributes - Alpine组件:如果使用自定义Alpine.js组件,请将输入字段放在组件外部,并通过原生JS更新
- 内置示例:参考中的内置处理器,使用经过验证的模式
Hyva_CmsLiveviewEditor::page/js/
Accurate Patterns from Codebase
来自代码库的准确模式
Based on built-in Hyvä CMS handler implementations:
-
Event Naming Convention: Usepattern
toggle-{type}-select- ✅ Correct: ,
toggle-product-select,toggle-link-selecttoggle-category-select - ❌ Incorrect: ,
toggle-product-handlertoggle-link-handler
- ✅ Correct:
-
Handler Function Naming: Usepattern
init{Type}Select()- ✅ Examples: ,
initProductSelect(),initLinkSelect()initCategorySelect()
- ✅ Examples:
-
Field Value Update Methods:
- Use (default): Products, Link, Category handlers
updateWireField- Triggers immediate server-side validation via Magewire
- Keeps component state synchronized
- Use (specialized): Image handler, debounced inputs (color, range)
updateField- Updates preview without server round-trip
- Defers validation until save
- Use
-
JSON Encoding Pattern: All complex data (arrays, objects) must be JSON-encodedphp
// Field template value="<?= $escaper->escapeHtmlAttr(json_encode($fieldValue)) ?>" // Handler initialization const data = JSON.parse(fieldValue); // @change handler @change="updateWireField(..., JSON.parse($event.target.value))" -
wire:ignore for Livewire Compatibility: Searchable select useswrapper
wire:ignorephp<div wire:ignore> <div x-data="initSearchableSelect(...)"> <!-- Alpine component --> </div> </div> -
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
- Field template:
-
Icons View Model: Use for UI elementsphp
/** @var Icons $icons */ $icons = $viewModels->require(Icons::class); <?= /** @noEscape */ $icons->trashHtml('', 22, 22) ?> -
FieldTypes View Model: Use for attribute filteringphp
/** @var FieldTypes $fieldTypes */ $fieldTypes = $viewModels->require(FieldTypes::class); $filteredAttributes = $fieldTypes->getDefinedFieldAttributes($attributes); // Or for specific attributes: $filteredAttributes = $fieldTypes->getAttributesByKeys($attributes, ['required', 'data-required']); -
CRITICAL: Layout XML referenceContainer: Handler modals MUST usecontainer
before.body.end- ✅ Correct:
<referenceContainer name="before.body.end"> - ❌ Incorrect:
<referenceContainer name="content"> - The 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
before.body.end
- ✅ Correct:
-
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 will fail when value is
(string), causing PHP errorsnull - Use for string values,
?? ''for array values, or appropriate default for your data type?? [] - Reference: See built-in field types like which use
category.phtmlpattern?? []
- CRITICAL: Dialog Modal Classes: Handler modals must use not static
open:flexclassflex
- ✅ Correct:
<dialog class="... open:flex flex-col"> - ❌ Incorrect: (modal always visible)
<dialog class="... flex flex-col"> - The prefix applies styles only when dialog is open (native HTML dialog state)
open: - Reference: See built-in handlers like which use
category-handler.phtmlopen:flex flex-col
- 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: without type checking (fails if value is already an array)
json_decode($fieldValue) - ❌ Incorrect: Using array directly in attribute without JSON-encoding first
value
基于Hyvä CMS内置处理器的实现:
-
事件命名规范:使用模式
toggle-{type}-select- ✅ 正确示例:,
toggle-product-select,toggle-link-selecttoggle-category-select - ❌ 错误示例:,
toggle-product-handlertoggle-link-handler
- ✅ 正确示例:
-
处理器函数命名:使用模式
init{Type}Select()- ✅ 示例:,
initProductSelect(),initLinkSelect()initCategorySelect()
- ✅ 示例:
-
字段值更新方法:
- 优先使用(默认):产品、链接、分类处理器
updateWireField- 通过Magewire触发即时服务器端验证
- 保持组件状态同步
- 使用(特殊场景):图片处理器、防抖输入(颜色、范围)
updateField- 无需服务器往返即可更新预览
- 延迟验证直到保存时
- 优先使用
-
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))" -
wire:ignore 兼容Livewire:可搜索选择器使用包装器
wire:ignorephp<div wire:ignore> <div x-data="initSearchableSelect(...)"> <!-- Alpine component --> </div> </div> -
独立处理器文件:即使是内联处理器也可能有独立的函数文件
- 字段模板:
liveview/field-types/searchable_select.phtml - 处理器函数:
page/js/searchable-select-handler.phtml
- 字段模板:
-
Icons 视图模型:用于UI元素php
/** @var Icons $icons */ $icons = $viewModels->require(Icons::class); <?= /** @noEscape */ $icons->trashHtml('', 22, 22) ?> -
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']); -
关键注意:布局XML referenceContainer:处理器模态框必须使用容器
before.body.end- ✅ 正确:
<referenceContainer name="before.body.end"> - ❌ 错误:
<referenceContainer name="content"> - 容器确保处理器模态框加载在页面body末尾,这是Alpine.js正确初始化和模态框功能正常的必要条件
before.body.end
- ✅ 正确:
-
关键注意:字段值类型处理:切勿对字段值使用类型转换,始终使用空值合并运算符
- ✅ 正确:
$fieldValue = $block->getData('value') ?? ''; - ❌ 错误:
$fieldValue = (string) $block->getData('value'); - 类型转换在值为
(string)时会失败,导致PHP错误null - 对于字符串值使用,数组值使用
?? '',或对应数据类型的合适默认值?? [] - 参考:类似的内置字段类型使用
category.phtml模式?? []
- ✅ 正确:
-
关键注意:对话框模态框类:处理器模态框必须使用而非静态
open:flex类flex- ✅ 正确:
<dialog class="... open:flex flex-col"> - ❌ 错误:(模态框始终可见)
<dialog class="... flex flex-col"> - 前缀仅在对话框打开时应用样式(原生HTML对话框状态)
open: - 参考:类似的内置处理器使用
category-handler.phtmlopen:flex flex-col
- ✅ 正确:
-
关键注意:复杂数据类型处理:对于存储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) - ❌ 错误:直接将数组用于属性而不先进行JSON编码
value