qhdtc5 2016-03-25 08:48:36 3708次浏览 1条回复 3 3 0

做一个UEditor的小组件(Widget)

最近一个项目需要用到富文本编辑器,一开始打算采用tinyMCE,可惜它没有上传功能,又没找到合适的插件,想开发吧自己又写不好JS,而UEditor可以满足我的需求,所以最后决定采用UEditor。

从网上找了几篇关于yii2和ueditor的文章,从发布assets到初始化UEditor,都是直接写到view文件中的,感觉这样并不是yii的风格,而且我的前后台都会用到这个编辑器,那样写就太不灵活了,就有了把它制作成一个Widget的想法,最后鼓捣了一天终于算是成功了,在这里把我的经验分享给大家。

下载和安装UEditor

下载就不用说了,直接下载最新的php版,这里我主要提一下安装。我的习惯是把widget的CSS和JS部分统一放在bower文件夹中,感觉更符合yii的风格,哈哈,所以我就在@bower文件夹下新建了baidu/ueditor文件夹,然后解压源代码到这里,如果使用ueditor自带的serverApi部分,就保留php文件夹,否则还是把它删了吧,总觉得有安全隐患。

UeditorAsset

在自己的namespace下创建UeditorAsset.php,我的namespace是vendor\wzapk\baidu\ueditor,代码如下:

namespace wzapk\baidu\ueditor;

use yii\web\AssetBundle;

class UeditorAsset extends AssetBundle
{
	public $sourcePath = '@bower/baidu/ueditor';

	public $js = [
		'ueditor.config.js',
		'ueditor.all.min.js',
	];
}
开始写关键的Ueditor类

这里我偷懒了,使用拿来主义,直接复制了yii2-jui的两个类当作自己的基类:Widget.php和InputWidget.php作为自己组件的基类,这两个类的代码我就不占用篇幅了,下面是Ueditor类的代码:

Ueditor.php


namespace wzapk\baidu\ueditor;

use wzapk\InputWidget;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\View;

class Ueditor extends InputWidget
{

	public function init()
	{
		parent::init();
	}

	public function run()
	{

		if ($this->hasModel()) {
            $value = Html::getAttributeValue($this->model, $this->attribute);
            $name = Html::getInputName($this->model, $this->attribute);
        } else {
            $value = $this->value;
            $name = $this->name;
        }

        $content[] = "<script id=\"{$this->options['id']}\" name=\"{$name}\" type=\"text/plain\">{$value}</script>";
        echo implode("\n", $content);

        $view = $this->getView();

		UeditorAsset::register($view);

		$options = Json::htmlEncode($this->clientOptions);
		$js = "UE.getEditor('{$this->options['id']}', $options);";
		$view->registerJs($js);

	}
}

代码很简单,生成html部分,最后发布相关文件和js代码。

使用

两种使用方法:


<?= Ueditor::widget(['model'=>$model, 'attribute'=>'model_data', 'clientOptions'=>[这里参考ueditor文档]]) ?>

<?= $form->field($model, 'model_data')->widget(Ueditor::className(), ['clientOptions'=>[这里参考ueditor文档]) ?>

UEditor的后台API部分

目前我还没研究,还在使用ueditor自带的API,请各位自行完成。

至此,Ueditor小组件完成了,符合YII思想,使用起来感觉很舒服,代码不是很成熟,欢迎大家指正,谢谢。

觉得很赞
您需要登录后才可以回复。登录 | 立即注册