You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony中CollectionField内的TextEditorType字段无法显示

问题

开发带有EasyAdmin控制台的Symfony项目时,为Campaign实体添加了CollectionField以实现Product的新增、编辑和删除操作。希望Product的description字段使用Symfony的TextEditorType来支持粗体、斜体等富文本格式,但该字段在EasyAdmin控制台中无法正常显示。

相关代码

Crud Controller代码

CollectionField::new('products', 'Products')
                    ->allowAdd()
                    ->allowDelete()
                    ->setEntryType(ProductType::class)
                    ->setFormTypeOptions([
                        'by_reference' => 'false'
                    ]),

ProductType代码

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, [
            "required" => true,
        ])
        ->add('description', TextEditorType::class, [
            "required" => true,
        ])
        ->add('tags', TextType::class, [
            "required" => true,
        ])
        ->add('price', TextType::class, [
            "required" => false,
        ]);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => Product::class,
    ]);
}
解决方案

1. 确认Symfony UX TextEditor组件已正确安装

TextEditorType依赖Symfony UX TextEditor组件,先执行安装命令:

composer require symfony/ux-text-editor

安装完成后构建前端资产:

npm install && npm run build
# 若使用yarn则执行:
yarn install && yarn build

2. 处理动态添加条目的编辑器初始化问题

EasyAdmin的CollectionField动态添加条目时,新的TextEditor不会自动初始化,需添加自定义JS处理:
在assets/app.js中加入以下代码:

import {initializeTextEditor} from '@symfony/ux-text-editor';

document.addEventListener('DOMContentLoaded', () => {
    // 初始化页面加载时已有的编辑器
    initializeTextEditor();
    
    // 监听CollectionField的条目添加事件,初始化新字段的编辑器
    document.addEventListener('ea.collection.item-added', (event) => {
        initializeTextEditor(event.detail.item);
    });
});

执行资产构建使修改生效:

npm run build

3. 修正FormType配置错误

by_reference选项需传入布尔值,而非字符串,修改Crud Controller中的配置:

->setFormTypeOptions([
    'by_reference' => false // 移除引号
]),

4. 清除Symfony缓存

执行缓存清除命令确保所有配置变更生效:

php bin/console cache:clear

内容的提问来源于stack exchange,提问作者Anass igli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:35:07