Joomla 核心提供 JEditor 類(libraries/joomla/html/editor.php),封裝了 TinyMCE、CodeMirror 等編輯器實現,供擴展開發者快速在表單中嵌入富文本編輯器。本文詳細說明 display() 方法參數、視圖調用方式、模板覆寫技巧及常見問題處理。
public static function display(
string $name, // 控件 name 屬性值
string $html, // 初始內容(HTML)
string $width, // 寬度(如 '100%'、'600px')
string $height, // 高度(如 '400px')
int $col, // textarea cols(備用)
int $row, // textarea rows(備用)
bool $buttons = true, // 是否顯示編輯器工具欄按鈕
string $id = null, // 控件 id,預設同 name
string $asset = null,// 資產名(用於 ACL 權限檢查)
object $author = null,// 作者對象
array $params = [] // 編輯器參數陣列(如 toolbar 配置)
): string
// view.html.php
class MyComponentViewForm extends JViewLegacy {
protected $form;
protected $item;
public function display($tpl = null) {
// 1. 獲取編輯器實例(單例模式)
$this->editor = JFactory::getEditor();
// 2. 可選:根據用戶權限動態調整參數
$user = JFactory::getUser();
if (!$user->authorise('core.edit', 'com_mycomponent')) {
$this->editorParams = ['buttons' => false]; // 僅顯示只讀
}
parent::display($tpl);
}
}
// tmpl/form.php
defined('_JEXEC') or die;
use Joomla\CMS\HTML\HTMLHelper;
$editor = $this->editor;
$fieldName = 'description';
$content = $this->item->description ?? '';
$width = '100%';
$height = '400px';
$col = 80;
$row = 20;
$buttons = true;
$id = $fieldName;
$asset = 'com_mycomponent.article.' . ($this->item->id ?? 0);
$author = JFactory::getUser();
// 輸出編輯器 HTML
echo $editor->display($fieldName, $content, $width, $height, $col, $row, $buttons, $id, $asset, $author, $this->editorParams ?? []);
$params 陣列可傳遞給底層編輯器插件(TinyMCE 為例):
$customParams = [
'toolbar' => 'undo redo | styleselect | bold italic | alignleft aligncenter alignright | bullist numlist | link image media | code',
'plugins' => 'link image media code table lists',
'content_css' => JUri::root() . 'media/com_mycomponent/css/editor-content.css',
'style_formats' => json_encode([
['title' => '標題 2', 'block' => 'h2', 'classes' => 'text-primary'],
['title' => '程式碼塊', 'block' => 'pre', 'classes' => 'language-php'],
]),
'relative_urls' => false,
'remove_script_host' => true,
];
echo $editor->display($name, $html, $width, $height, $col, $row, $buttons, $id, $asset, $author, $customParams);
layouts/joomla/editors/tinymce.php 至你的模板:templates/your_template/html/layouts/joomla/editors/tinymce.php| 問題 | 原因 | 解決 |
|---|---|---|
| 編輯器不顯示/報錯 | 未加載 Mootools/jQuery、JS 衝突 | 確保模板包含 JHtml::_('behavior.framework');檢查瀏覽器控制台錯誤 |
| 圖片上傳按鈕無效 | 缺少媒體管理器權限或路徑配置 | 檢查用戶組權限 core.create、core.edit;配置 media 插件路徑 |
| 內容儲存後 HTML 被過濾 | 全局文本過濾器設置 | 系統 → 全局配置 → 文本過濾器,將該用戶組設為「無過濾」 |
| 編輯器語言非中文 | 語言包缺失或用戶語言設置 | 安裝對應語言包;用戶後台語言設置為 zh-CN |
| AJAX 動態載入表單編輯器不初始化 | JS 未重新綁定 | AJAX 成功回調中執行 Joomla.editors.instances[editorId].init() 或重新調用 JFactory::getEditor()->display() |
Joomla\CMS\Editor\Editor 與 Joomla\CMS\Factory。$editor = Factory::getContainer()->get(Editor::class)。掌握 JEditor::display() 參數含義、視圖層實例化、模板覆寫機制、權限與過濾器配置,即可在 Joomla 擴展中靈活嵌入功能完整的富文本編輯器。遵循「不修改核心、善用覆寫、配置權限」原則,確保升級安全與長期可維護性。