Yii2自定义Widget,百度编辑器



本文抄自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异常

  1. 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 属性自定义发布位置。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值