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

Laravel中CKEditor的getData()方法与withInput回显均失效问题求助

问题原因

CKEditor初始化时会替换页面上的原始表单元素(text/textarea),生成独立的富文本编辑区,默认不会主动读取原始表单元素上通过old()渲染的历史提交值,因此会出现withInput()回显失效的问题。


解决方案

1. 修正表单元素类型

富文本字段应使用textarea而非text输入框承载内容,同时修正你代码中$language>id的语法错误,修改后的表单代码如下:

<?php echo Form::textarea("PageLanguage[description][$language->id]",
old("PageLanguage[description][$language->id]"), 
array('id' => "description-$language->id",'class' => 'form-control'));
?>

2. 初始化CKEditor时手动同步回显内容

在CKEditor实例初始化完成的回调中,读取原始textarea的内容(即old()渲染的历史提交值),赋值给CKEditor编辑区即可:

CKEditor 4 示例代码
document.addEventListener('DOMContentLoaded', function () {
  // 匹配所有description开头的富文本字段
  document.querySelectorAll('[id^="description-"]').forEach(textarea => {
    const editorId = textarea.id;
    // 避免重复初始化报错
    if (window.CKEDITOR?.instances[editorId]) {
      CKEDITOR.remove(CKEDITOR.instances[editorId]);
    }
    const editor = CKEDITOR.replace(editorId);
    // 编辑器就绪后设置回显内容
    editor.on('instanceReady', function () {
      this.setData(textarea.value);
    });
  });
});
CKEditor 5 示例代码
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('[id^="description-"]').forEach(async textarea => {
    const editor = await ClassicEditor.create(textarea);
    editor.setData(textarea.value);
  });
});

3. 提交时确保内容同步

如果是AJAX提交表单,需要在提交前调用editor.getData()获取富文本内容,赋值给原始textarea后再提交,避免提交内容和编辑内容不一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:24:03