热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

YII视图整合kindeditor扩展的方法

这篇文章主要介绍了YII视图整合kindeditor扩展的方法,较为详细的分析了Yii框架整合kindeditor的功能实现代码与设置相关技巧,需要的朋友可以参考下

本文实例讲述了YII视图整合kindeditor扩展的方法。分享给大家供大家参考,具体如下:

比较喜欢用kindeditor,YII上的版本比较旧,所以自己重新整了个扩展
先在protected\extensions下创建KEditor文件夹用来放文件,keSource里放kindeditor的源文件,然后建三个类KEditor、KEditorManage和KEditorUpload,KEditor是扩展的主文件,KEditorManage是用来浏览服务器文件的,KEditorUpload是用来示例接收上传文件的,

KEditor代码

<&#63;php
class KEditor extends CWidget{
  /*
   * TEXTAREA输入框的属性,保证js调用KE失败时,文本框的样式。
   */
  public $textareaOptiOns=array();
  /*
   * 编辑器属性集。
   */
  public $properties=array();
  /*
   * TEXTAREA输入框的name,必须设置。
   * 数据类型:String
   */
  public $name;
  /*
   * TEXTAREA的id,可为空
   */
  public $id;
  public $model;
  public $baseUrl;
  public static function getUploadPath(){
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
    if(isset(Yii::app()->params->uploadPath)){
      return Yii::getPathOfAlias('webroot').str_replace(
                '/',DIRECTORY_SEPARATOR,
                Yii::app()->params->
                uploadPath);
    }
    return Yii::app()->getAssetmanager()
        ->getPublishedPath($dir).DIRECTORY_SEPARATOR.'upload';
  }
  public static function getUploadUrl(){
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
    if(isset(Yii::app()->params->uploadPath)){
      return Yii::app()->baseUrl.Yii::app()->params->uploadPath;
    }
    return Yii::app()->getAssetManager()->publish($dir).'/upload';
  }
  public function init(){
    if($this->name===null)
      throw new CException(Yii::t('zii','The id property cannot be empty.'));
    $dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'keSource';
    $this->baseUrl=Yii::app()->getAssetManager()->publish($dir);
    $cs=Yii::app()->getClientScript();
    $cs->registerCssFile($this->baseUrl.'/themes/default/default.css');
    if(YII_DEBUG) $cs->registerScriptFile($this->baseUrl.'/kindeditor.js');
    else $cs->registerScriptFile($this->baseUrl.'/kindeditor-min.js');
  }
  public function run(){
    $cs=Yii::app()->getClientScript();
    $textAreaOptiOns=$this->gettextareaOptions();
    $textAreaOptions['name']=CHtml::resolveName($this->model,$this->name);
    $this->id=$textAreaOptions['id']=CHtml::getIdByName($textAreaOptions['name']);
    echo CHtml::activeTextArea($this->model,$this->name,$textAreaOptions);
    $properties_string = CJavascript::encode($this->getKeProperties());
    $js=<<id = K.create('#$this->id',
$properties_string
  );
});
EOF;
    $cs->registerScript('KE'.$this->name,$js,CClientScript::POS_HEAD);
  }
  public function gettextareaOptions(){
    //允许获取的属性
    $allowParams=array('rows','cols','style');
    //准备返回的属性数组
    $params=array();
    foreach($allowParams as $key){
      if(isset($this->textareaOptions[$key]))
        $params[$key]=$this->textareaOptions[$key];
    }
    $params['name']=$params['id']=$this->name;
    return $params;
  }
  public function getKeProperties(){
    $properties_key=array(
      'width',
      'height',
      'minWidth',
      'minHeight',
      'items',
      'noDisableItems',
      'filterMode',
      'htmlTags',
      'wellFormatMode',
      'resizeType',
      'themeType',
      'langType',
      'designMode',
      'fullscreenMode',
      'basePath',
      'themesPath',
      'pluginsPath',
      'langPath',
      'minChangeSize',
      'urlType',
      'newlineTag',
      'pasteType',
      'dialogAlignType',
      'shadowMode',
      'useContextmenu',
      'syncType',
      'indentChar',
      'cssPath',
      'cssData',
      'bodyClass',
      'colorTable',
      'afterCreate',
      'afterChange',
      'afterTab',
      'afterFocus',
      'afterBlur',
      'afterUpload',
      'uploadJson',
      'fileManagerJson',
      'allowPreviewEmoticons',
      'allowImageUpload',
      'allowFlashUpload',
      'allowMediaUpload',
      'allowFileUpload',
      'allowFileManager',
      'fontSizeTable',
      'imageTabIndex',
      'formatUploadUrl',
      'fullscreenShortcut',
      'extraFileUploadParams',
    );
    //准备返回的属性数组
    $params=array();
    foreach($properties_key as $key){
      if(isset($this->properties[$key]))
        $params[$key]=$this->properties[$key];
    }
    return $params;
  }
}

KEditorManage代码

<&#63;php
class KEditorManage extends CAction{
  public function run(){
    Yii::import('ext.KEditor.KEditor');
    $root_path=KEditor::getUploadPath().'/';
    $root_url=KEditor::getUploadUrl().'/';
    //图片扩展名
    $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
    //目录名
    $dir_name = empty($_GET['dir']) &#63; '' : trim($_GET['dir']);
    if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
      echo "Invalid Directory name.";
      exit;
    }
    if ($dir_name !== '') {
      $root_path .= $dir_name . "/";
      $root_url .= $dir_name . "/";
      if (!file_exists($root_path)) {
        mkdir($root_path);
      }
    }
    //根据path参数,设置各路径和URL
    if (empty($_GET['path'])) {
      $current_path = realpath($root_path) . '/';
      $current_url = $root_url;
      $current_dir_path = '';
      $moveup_dir_path = '';
    } else {
      $current_path = realpath($root_path) . '/' . $_GET['path'];
      $current_url = $root_url . $_GET['path'];
      $current_dir_path = $_GET['path'];
      $moveup_dir_path = preg_replace('/(.*&#63;)[^\/]+\/$/', '$1', $current_dir_path);
    }
    echo realpath($root_path);
    //排序形式,name or size or type
    $order = empty($_GET['order']) &#63; 'name' : strtolower($_GET['order']);
    //不允许使用..移动到上一级目录
    if (preg_match('/\.\./', $current_path)) {
      echo 'Access is not allowed.';
      exit;
    }
    //最后一个字符不是/
    if (!preg_match('/\/$/', $current_path)) {
      echo 'Parameter is not valid.';
      exit;
    }
    //目录不存在或不是目录
    if (!file_exists($current_path) || !is_dir($current_path)) {
      echo 'Directory does not exist.';
      exit;
    }
    //遍历目录取得文件信息
    $file_list = array();
    $handle = new DirectoryIterator($current_path);
    $i=0;
    foreach($handle as $file){
      if($file->isDot()) continue;
      if($file->isDir()){
        $file_list[$i]['is_dir'] = true; //是否文件夹
        $file_list[$i]['has_file'] = (count(scandir($file->getPath())) > 2); //文件夹是否包含文件
        $file_list[$i]['filesize'] = 0; //文件大小
        $file_list[$i]['is_photo'] = false; //是否图片
        $file_list[$i]['filetype'] = ''; //文件类别,用扩展名判断
      }else{
        $file_list[$i]['is_dir'] = false;
        $file_list[$i]['has_file'] = false;
        $file_list[$i]['filesize'] = $file->getSize();
        $file_list[$i]['dir_path'] = '';
        $file_ext = $file->getExtension();
        $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
        $file_list[$i]['filetype'] = $file_ext;
      }
      $file_list[$i]['filename'] = $file->getFilename(); //文件名,包含扩展名
      $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file->getMTime());
      $i++;
    }
    usort($file_list, array($this,'cmp_func'));
    $result = array();
    //相对于根目录的上一级目录
    $result['moveup_dir_path'] = $moveup_dir_path;
    //相对于根目录的当前目录
    $result['current_dir_path'] = $current_dir_path;
    //当前目录的URL
    $result['current_url'] = $current_url;
    //文件数
    $result['total_count'] = count($file_list);
    //文件列表数组
    $result['file_list'] = $file_list;
    //输出JSON字符串
    header('Content-type: application/json; charset=UTF-8');
    echo CJSON::encode($result);
    exit;
  }
  //排序
  public function cmp_func($a, $b) {
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
      return -1;
    } else if (!$a['is_dir'] && $b['is_dir']) {
      return 1;
    } else {
      if ($order == 'size') {
        if ($a['filesize'] > $b['filesize']) {
          return 1;
        } else if ($a['filesize'] <$b['filesize']) {
          return -1;
        } else {
          return 0;
        }
      } else if ($order == 'type') {
        return strcmp($a['filetype'], $b['filetype']);
      } else {
        return strcmp($a['filename'], $b['filename']);
      }
    }
  }
}
&#63;>

KEditorUpload代码

<&#63;php
class KEditorUpload extends CAction{
  public function run(){
    $dir=isset($_GET['dir'])&#63;trim($_GET['dir']):'file';
    $ext_arr = array(
      'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
      'flash' => array('swf', 'flv'),
      'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
      'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
    );
    if(empty($ext_arr[$dir])){
      echo CJSON::encode(array('error'=>1,'message'=>'目录名不正确。'));
      exit;
    }
    $originalurl='';
    $filename='';
    $date=date('Ymd');
    $id=0;
    $max_size=2097152; //2MBs
    $upload_image=CUploadedFile::getInstanceByName('imgFile');
    Yii::import('ext.KEditor.KEditor');
    $upload_dir=KEditor::getUploadPath().'/'.$dir;
    if(!file_exists($upload_dir)) mkdir($upload_dir);
    $upload_dir=$upload_dir.'/'.$date;
    if(!file_exists($upload_dir)) mkdir($upload_dir);
    $upload_url=KEditor::getUploadUrl().'/'.$dir.'/'.$date;
    if(is_object($upload_image) && get_class($upload_image)==='CUploadedFile'){
      if($upload_image->size > $max_size){
        echo CJSON::encode(array('error'=>1,'message'=>'上传文件大小超过限制。'));
        exit;
      }
      //新文件名
      $filename=date("YmdHis").'_'.rand(10000, 99999);
      $ext=$upload_image->extensionName;
      if(in_array($ext, $ext_arr[$dir]) === false){
        echo CJSON::encode(array('error'=>1,'message'=>"上传文件扩展名是不允许的扩展名。\n只允许".implode(',',$ext_arr[$dir]).'格式。'));
        exit;
      }
      $uploadfile=$upload_dir.'/'.$filename.'.'.$ext;
      $originalurl=$upload_url.'/'.$filename.'.'.$ext;
      $upload_image->saveAs($uploadfile);
      echo CJSON::encode(array('error'=>0,'url'=>$originalurl));
    }else{
      echo CJSON::encode(array('error'=>1,'message'=>'未知错误'));
    }
  }
}

配置config/main.php文件,设置上传文件存放位置

'params'=>array(
    // this is used in contact page
    'adminEmail'=>'webmaster@example.com',
    'uploadPath'=>'/upload', //添加这句,upload为存放文件文件夹的名字,自己定义,这里是放在根目录的upload文件夹

设置接收文件和浏览服务器文件的action

public function actions()
{
  return array(
    //在actions下的return array添加下面两句,没有actions的话自己添加
    'upload'=>array('class'=>'application.extensions.KEditor.KEditorUpload'),
    'manageJson'=>array('class'=>'application.extensions.KEditor.KEditorManage'),
  );
}

在视图里面使用

<&#63;php $this->widget('ext.KEditor.KEditor',array(
  'model'=>$model, //传入form model
  'name'=>'content', //设置name
  'properties'=>array(
    //设置接收文件上传的action
    'uploadJson'=>'/admin/default/upload',
    //设置浏览服务器文件的action,这两个就是上面配置在/admin/default的
    'fileManagerJson'=>'/admin/default/manageJson',
    'newlineTag'=>'br',
    'allowFileManager'=>true,
    //传值前加js:来标记这些是js代码
    'afterCreate'=>"js:function() {
        K('#ChapterForm_all_len').val(this.count());
        K('#ChapterForm_word_len').val(this.count('text'));
      }",
    'afterChange'=>"js:function() {
        K('#ChapterForm_all_len').val(this.count());
        K('#ChapterForm_word_len').val(this.count('text'));
      }",
  ),
  'textareaOptions'=>array(
    'style'=>'width:98%;height:400px;',
  )
));
&#63;>

textareaOptions用来设置textarea的大小和样式,仅支持rows、cols和style
properties的各项跟js设置kindeditor的是一样的,上面的设置与下面用js设置的是一致,kindeditor原来有的项都可以设置

var editor1 = K.create('#editor_modelname_name', {
  uploadJson : "/admin/default/upload",
  fileManagerJson : "/admin/default/manageJson",
  newlineTag : "br",
  allowFileManager : true,
  afterCreate : function() {
    K('#ChapterForm_all_len').html(this.count());
    K('#ChapterForm_word_len').html(this.count('text'));
  },
  afterChange : function() {
    K('#ChapterForm_all_len').html(this.count());
    K('#ChapterForm_word_len').html(this.count('text'));
  }
});

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。


推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了通过ABAP开发往外网发邮件的需求,并提供了配置和代码整理的资料。其中包括了配置SAP邮件服务器的步骤和ABAP写发送邮件代码的过程。通过RZ10配置参数和icm/server_port_1的设定,可以实现向Sap User和外部邮件发送邮件的功能。希望对需要的开发人员有帮助。摘要长度:184字。 ... [详细]
  • PDF内容编辑的两种小方法,你知道怎么操作吗?
    本文介绍了两种PDF内容编辑的方法:迅捷PDF编辑器和Adobe Acrobat DC。使用迅捷PDF编辑器,用户可以通过选择需要更改的文字内容并设置字体形式、大小和颜色来编辑PDF文件。而使用Adobe Acrobat DC,则可以通过在软件中点击编辑来编辑PDF文件。PDF文件的编辑可以帮助办公人员进行文件内容的修改和定制。 ... [详细]
  • 本文介绍了一个免费的asp.net控件,该控件具备数据显示、录入、更新、删除等功能。它比datagrid更易用、更实用,同时具备多种功能,例如属性设置、数据排序、字段类型格式化显示、密码字段支持、图像字段上传和生成缩略图等。此外,它还提供了数据验证、日期选择器、数字选择器等功能,以及防止注入攻击、非本页提交和自动分页技术等安全性和性能优化功能。最后,该控件还支持字段值合计和数据导出功能。总之,该控件功能强大且免费,适用于asp.net开发。 ... [详细]
  • 使用chrome编辑器实现网页截图功能的方法
    本文介绍了在chrome浏览器中使用编辑器实现网页截图功能的方法。通过在地址栏中输入特定命令,打开控制台并调用命令面板,用户可以方便地进行网页截图操作。 ... [详细]
  • Linux环境变量$PATH的作用及使用方法
    本文介绍了Linux环境变量$PATH的作用及使用方法。$PATH是一个由多个目录组成的变量,用冒号分隔。当执行一个指令时,系统会按照$PATH定义的目录顺序搜索同名的可执行文件,如果有多个同名指令,则先找到的会被执行。通过设置$PATH变量,可以在任何地方执行指令,无需输入绝对路径。 ... [详细]
  • Unity3D引擎的体系结构和功能详解
    本文详细介绍了Unity3D引擎的体系结构和功能。Unity3D是一个屡获殊荣的工具,用于创建交互式3D应用程序。它由游戏引擎和编辑器组成,支持C#、Boo和JavaScript脚本编程。该引擎涵盖了声音、图形、物理和网络功能等主题。Unity编辑器具有多语言脚本编辑器和预制装配系统等特点。本文还介绍了Unity的许可证情况。Unity基本功能有限的免费,适用于PC、MAC和Web开发。其他平台或完整的功能集需要购买许可证。 ... [详细]
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 如何实现JDK版本的切换功能,解决开发环境冲突问题
    本文介绍了在开发过程中遇到JDK版本冲突的情况,以及如何通过修改环境变量实现JDK版本的切换功能,解决开发环境冲突的问题。通过合理的切换环境,可以更好地进行项目开发。同时,提醒读者注意不仅限于1.7和1.8版本的转换,还要适应不同项目和个人开发习惯的需求。 ... [详细]
  • Windows7企业版怎样存储安全新功能详解
    本文介绍了电脑公司发布的GHOST WIN7 SP1 X64 通用特别版 V2019.12,软件大小为5.71 GB,支持简体中文,属于国产软件,免费使用。文章还提到了用户评分和软件分类为Win7系统,运行环境为Windows。同时,文章还介绍了平台检测结果,无插件,通过了360、腾讯、金山和瑞星的检测。此外,文章还提到了本地下载文件大小为5.71 GB,需要先下载高速下载器才能进行高速下载。最后,文章详细解释了Windows7企业版的存储安全新功能。 ... [详细]
author-avatar
PHPdudu
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有