KilluaCHEN 2015-07-05 10:55:47 15877次浏览 2条评论 21 13 0

小部件是在视图中使用的可重用单元,使用面向对象方式创建复杂和可配置用户界面单元。

官方给出了很多写好的组件,如Nav,Modal,ActiveForm... 查看更多 ,但远远满足不了我们的需求,所以今天给大家带来自定义组件(Ueditor)

在项目开发过程中,少不了富文本编辑器的存在,下面我们就来创建一个Ueditor组件

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

原文链接

觉得很赞
  • 评论于 2016-03-09 10:29 举报

    问一下,上传接口怎么办?用百度带的php代码,还是自己写,如果用百度的,怎样保证是授权的人才能调用上传接口呢?
    另外,我看它默认的地址是去js下找的上传接口,我不想在web目录有放太多的PHP脚本。

  • 评论于 2018-02-02 17:30 举报

    用不了耶。

您需要登录后才可以评论。登录 | 立即注册