How to use kindeditor extension in YII
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')); } });
相关推荐:
The above is the detailed content of How to use kindeditor extension in YII. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension
