YII如何使用kindeditor扩展?本文主要介绍了YII视图整合kindeditor扩展的方法,较为详细的分析了Yii框架整合kindeditor的功能实现代码与设置相关技巧,需要的朋友可以参考下。希望对大家有所帮助。
具体如下:
比较喜欢用kindeditor,YII上的版本比较旧,所以自己重新整了个扩展
先在protected\extensions下创建KEditor文件夹用来放文件,keSource里放kindeditor的源文件,然后建三个类KEditor、KEditorManage和KEditorUpload,KEditor是扩展的主文件,KEditorManage是用来浏览服务器文件的,KEditorUpload是用来示例接收上传文件的,
KEditor代码
<?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=<<<EOF KindEditor.ready(function(K) { var editor_$this->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代码
<?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']) ? '' : 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('/(.*?)[^\/]+\/$/', '$1', $current_dir_path); } echo realpath($root_path); //排序形式,name or size or type $order = empty($_GET['order']) ? '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']); } } } } ?>
KEditorUpload代码
<?php class KEditorUpload extends CAction{ public function run(){ $dir=isset($_GET['dir'])?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'), ); }
在视图里面使用
<?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;', ) )); ?>
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如何使用kindeditor扩展的详细内容。更多信息请关注PHP中文网其他相关文章!

PHP的SNMP扩展是一种使PHP能够通过SNMP协议与网络设备进行通信的扩展程序。使用该扩展可以方便地获取和修改网络设备的配置信息,例如路由器、交换机等设备的CPU、内存、网络接口等信息,也可以进行诸如开关设备端口等控制操作。本文将介绍SNMP协议的基础知识、PHP的SNMP扩展的安装方法以及如何在PHP中使用SNMP扩展进行网络设备的监控和控制。一、SN

如何使用极光推送扩展,在PHP应用中实现批量消息推送功能在移动应用的开发中,消息推送是一项非常重要的功能。极光推送是一种常用的消息推送服务,提供了丰富的功能和接口。本文将介绍如何使用极光推送扩展在PHP应用中实现批量消息推送功能。第一步:注册极光推送账号并获取API密钥首先,我们需要在极光推送官网(https://www.jiguang.cn/push)注册

PHP是一种流行的服务器端语言,可以用来开发Web应用程序和处理文件。PHP的ZipArchive扩展是一个强大的工具,可以在PHP中操作zip文件。在这篇文章中,我们将介绍如何使用PHP的ZipArchive扩展来创建、读取和修改zip文件。一、安装ZipArchive扩展在使用ZipArchive扩展之前,需要确保已经安装了这个扩展。安装方法如下:1.安

PHP的POSIX扩展是一组允许PHP与POSIX兼容操作系统进行交互的函数和常量。POSIX(PortableOperatingSystemInterface)是一组操作系统接口标准,旨在允许软件开发人员编写可在各种UNIX或UNIX类操作系统上运行的应用程序。本文将介绍如何使用PHP的POSIX扩展,包括安装和使用。一、安装PHP的POSIX扩展在

随着PHP的发展和应用场景的不断扩大,Phar扩展已经成为PHP编程中的重要一环。Phar是PHPArchive的缩写,它可以将多个PHP文件和资源打包成单个文件,方便进行分发和管理。本文将介绍如何使用PHP的Phar扩展来进行打包和管理。安装Phar扩展首先,我们需要检查PHP是否已经安装Phar扩展。在Linux下,通过终端输入以下命令:php-m

教程:使用百度云推送(BaiduPush)扩展在PHP应用中实现消息推送功能引言:随着移动应用的迅猛发展,消息推送功能在应用程序中变得越来越重要。为了实现即时通知和消息推送功能,百度提供了一种强大的云推送服务,即百度云推送(BaiduPush)。在本教程中,我们将学习如何使用百度云推送扩展(PHPSDK)在PHP应用中实现消息推送功能。我们将使用百度云

PHP和WebDriver扩展:如何模拟用户点击和输入操作近年来,随着Web应用程序的快速发展,自动化测试变得越来越重要。在自动化测试中,模拟用户操作是一个关键的环节,它可以使我们更准确地测试和验证我们的应用程序。在PHP开发中,我们通常使用SeleniumWebDriver来实现自动化测试。SeleniumWebDriver是一种强大的工具,它可以模拟

随着前端技术的不断发展,Vue已经成为了前端开发中的热门框架之一。在Vue中,组件是其中的核心概念之一,它可以将页面分解为更小,更易管理的部分,从而提高开发效率和代码复用性。本文将重点介绍Vue如何实现组件的复用和扩展。一、Vue组件复用mixinsmixins是Vue中的一种共享组件选项的方式。Mixins允许将多个组件的组件选项合并成一个对象,从而最大


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6
视觉化网页开发工具

禅工作室 13.0.1
功能强大的PHP集成开发环境