本文抄自yii Framework中文社区,记录在此,方便日后查用
1.把下载好的Ueditor放在 应用/web 目录下
2.在项目应用下创建component目录,分别创建Ueditor.php和UeditorAsset.php文件,依次写入
namespace demo\components;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;
class Ueditor extends InputWidget
{
public $attributes;
public function init()
{
parent::init();
}
public function run()
{
$view = $this->getView();
$this->attributes['id']=$this->options['id'];
if($this->hasModel()){
$input=Html::activeTextarea($this->model, $this->attribute,$this->attributes);
}else{
$input=Html::textarea($this->name,'',$this->attributes);
}
echo $input;
UeditorAsset::register($view);//将Ueditor用到的脚本资源输出到视图
$js='var ue = UE.getEditor("'.$this->options['id'].'",'.$this->getOptions().');';//Ueditor初始化脚本
$view->registerJs($js, $view::POS_END);//将Ueditor初始化脚本也响应到视图中
}
public function getOptions()
{
unset($this->options['id']);//Ueditor识别不了id属性,故而删之
return Json::encode($this->options);
}
}
namespace demo\components;
use yii\web\AssetBundle;
class UeditorAsset extends AssetBundle
{
public $js = [
'ueditor.config.js',
'ueditor.all.js',
];
public $css = [
];
public function init()
{
$this->sourcePath =$_SERVER['DOCUMENT_ROOT'].\Yii::getAlias('@web').'/ueditor'; //设置资源所处的目录
}
}
注意: 命名空间一定要和文件所在的目录结构是一致的,否则会出现Class not found异常
- View中使用
非ActiveForm(name和id参数必须传递,用来控制初始化脚本)
use demo\components\Ueditor;
echo Ueditor::widget([
'name'=>'content',
'options'=>[
'id'=>'txtContent',
'focus'=>true,
'toolbars'=> [
['fullscreen', 'source', 'undo', 'redo', 'bold']
],
],
'attributes'=>[
'style'=>'height:80px'
]
]);
ActiveForm中
$form->field($model, 'content')->widget(Ueditor::className(),[
'options'=>[
'focus'=>true,
'toolbars'=> [
['fullscreen', 'source', 'undo', 'redo', 'bold']
],
],
'attributes'=>[
'style'=>'height:80px'
]
])
总结:
自定义组件的过程很简单,我们拿Ueditor举例,步骤如下
1.输出 input 控件
2.注册 Ueditor 用到的脚本文件
3.注册 Ueditor 初始化脚本
4.定义好变量,传递参数(完善组件)
Ueditor更多属性及设置见:http://fex.baidu.com/ueditor/#start-config
更新
在UeditorAsset中不是设置sourcePath而是设置basePath和baseUrl,就不会将资源发布到asserts中去。因为这个导致好几次调试时修改了代码不起作用,才发现页面调用的是asserts中随机文件夹中的代码,而不是放在本地的源代码。
摘自中文文档:
资源发布
如前所述,如果资源包放在Web不能访问的目录,当视图注册资源时资源会被拷贝到一个Web可访问的目录中, 这个过程称为资源发布,yii\web\AssetManager会自动处理该过程。
资源默认会发布到@webroot/assets
目录,对应的URL为@web/assets
, 可配置yii\web\AssetManager::basePath 和 yii\web\AssetManager::baseUrl 属性自定义发布位置。