我想在微型 mce 编辑器中添加自定义下拉菜单,我正在使用 yii 框架并使用 yii 插件来集成编辑器
您可以使用
TinyMCE
选项在 setup
中添加下拉菜单,该选项采用带有参数 editor
的回调函数,该参数保存编辑器实例,然后您需要使用要创建的选项调用 editor.addButton(label, options)
自定义下拉按钮。
由于您没有在问题中添加任何详细信息,例如您将在下拉列表中显示哪些选项,因此,我将在此处假设变量
usernames
中数据库中的 $users
。
实施步骤
$users
将yii\helpers\Json::encode()
数组转换为js数组。onclick
事件创建下拉选项,以将内容插入编辑器。editor.addButton('users',options)
创建一个带有标签 users
的下拉类型按钮,以便稍后在初始化编辑器工具栏按钮时使用。在视图顶部添加以下代码
$usersList = \yii\helpers\Json::encode($users);
$tinyMCECallback = <<< JS
function (editor) {
let usersList = $usersList;
let options = [];
//iterate the user array and create the options with text and
//onclick event to insert the content on click to the editor
$.each(usersList, function(label, mapping) {
options.push({
text: label,
onclick: function() { tinymce.activeEditor.insertContent(label); }
});
});
//add the dropdown button to the editor
editor.addButton('users', {
type: 'menubutton',
text: 'Users',
icon: false,
menu: options
});
}
JS;
现在您需要做的就是将
$tinyMCECallback
传递给 setup
小部件的 tinyMCE
选项,如果您使用的是活动表单,您的代码应如下所示。
注意:不要忘记将按钮的
users
标签添加到工具栏选项中,或者如果您在 javascript 代码中更改它,请在编辑器工具栏选项中进行相应更改,否则它将不会显示
<?php
echo $form->field(
$model, 'body'
)->widget(
TinyMce::class, [
'options' => ['rows' => 10],
'language' => 'en',
'clientOptions' => [
'menubar' => false,
'statusbar' => false,
'toolbar' => "undo redo | users",
'setup' => new \yii\web\JsExpression($tinyMCECallback),
],
]
);
?>