YII視圖整合kindeditor擴(kuò)展的方法
本文實(shí)例講述了YII視圖整合kindeditor擴(kuò)展的方法。分享給大家供大家參考,具體如下:
比較喜歡用kindeditor,YII上的版本比較舊,所以自己重新整了個(gè)擴(kuò)展
先在protected\extensions下創(chuàng)建KEditor文件夾用來(lái)放文件,keSource里放kindeditor的源文件,然后建三個(gè)類(lèi)KEditor、KEditorManage和KEditorUpload,KEditor是擴(kuò)展的主文件,KEditorManage是用來(lái)瀏覽服務(wù)器文件的,KEditorUpload是用來(lái)示例接收上傳文件的,
KEditor代碼
<?php class KEditor extends CWidget{ /* * TEXTAREA輸入框的屬性,保證js調(diào)用KE失敗時(shí),文本框的樣式。 */ public $textareaOptions=array(); /* * 編輯器屬性集。 */ public $properties=array(); /* * TEXTAREA輸入框的name,必須設(shè)置。 * 數(shù)據(jù)類(lèi)型: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'); //準(zhǔn)備返回的屬性數(shù)組 $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', ); //準(zhǔn)備返回的屬性數(shù)組 $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().'/'; //圖片擴(kuò)展名 $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); } } //根據(jù)path參數(shù),設(shè)置各路徑和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']); //不允許使用..移動(dòng)到上一級(jí)目錄 if (preg_match('/\.\./', $current_path)) { echo 'Access is not allowed.'; exit; } //最后一個(gè)字符不是/ 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'] = ''; //文件類(lèi)別,用擴(kuò)展名判斷 }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(); //文件名,包含擴(kuò)展名 $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file->getMTime()); $i++; } usort($file_list, array($this,'cmp_func')); $result = array(); //相對(duì)于根目錄的上一級(jí)目錄 $result['moveup_dir_path'] = $moveup_dir_path; //相對(duì)于根目錄的當(dāng)前目錄 $result['current_dir_path'] = $current_dir_path; //當(dāng)前目錄的URL $result['current_url'] = $current_url; //文件數(shù) $result['total_count'] = count($file_list); //文件列表數(shù)組 $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'=>'上傳文件大小超過(guò)限制。')); 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'=>"上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\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'=>'未知錯(cuò)誤')); } } }
配置config/main.php文件,設(shè)置上傳文件存放位置
'params'=>array( // this is used in contact page 'adminEmail'=>'webmaster@example.com', 'uploadPath'=>'/upload', //添加這句,upload為存放文件文件夾的名字,自己定義,這里是放在根目錄的upload文件夾
設(shè)置接收文件和瀏覽服務(wù)器文件的action
public function actions() { return array( //在actions下的return array添加下面兩句,沒(méi)有actions的話(huà)自己添加 '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', //設(shè)置name 'properties'=>array( //設(shè)置接收文件上傳的action 'uploadJson'=>'/admin/default/upload', //設(shè)置瀏覽服務(wù)器文件的action,這兩個(gè)就是上面配置在/admin/default的 'fileManagerJson'=>'/admin/default/manageJson', 'newlineTag'=>'br', 'allowFileManager'=>true, //傳值前加js:來(lái)標(biāo)記這些是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用來(lái)設(shè)置textarea的大小和樣式,僅支持rows、cols和style
properties的各項(xiàng)跟js設(shè)置kindeditor的是一樣的,上面的設(shè)置與下面用js設(shè)置的是一致,kindeditor原來(lái)有的項(xiàng)都可以設(shè)置
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')); } });
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Yii框架入門(mén)及常用技巧總結(jié)》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《smarty模板入門(mén)基礎(chǔ)教程》、《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
- Yii框架視圖、視圖布局、視圖數(shù)據(jù)塊操作示例
- Yii框架的布局文件實(shí)例分析
- PHP的Yii框架中View視圖的使用進(jìn)階
- PHP的Yii框架中創(chuàng)建視圖和渲染視圖的方法詳解
- Yii控制器中操作視圖js的方法
- Yii視圖操作之自定義分頁(yè)實(shí)現(xiàn)方法
- Yii2框架視圖(View)操作及Layout的使用方法分析
- Yii視圖CGridView實(shí)現(xiàn)操作按鈕定義地址示例
- Yii視圖CGridView列表用法實(shí)例分析
- YII框架學(xué)習(xí)筆記之命名空間、操作響應(yīng)與視圖操作示例
- Yii框架布局文件的動(dòng)態(tài)切換操作示例
相關(guān)文章
phpcms手機(jī)內(nèi)容頁(yè)面添加上一篇和下一篇
本文給大家分享的是在phpcms中的手機(jī)內(nèi)容詳情頁(yè)里添加上一篇和下一篇的方法,十分的簡(jiǎn)單實(shí)用,有需要的小伙伴可以參考下。2015-06-06php 使用mpdf實(shí)現(xiàn)指定字段配置字體樣式的方法
前兩天在做一個(gè)pdf導(dǎo)出功能,使用的插件是kartik-v/yii2-mpdf,此插件使用的是mpdf。接下來(lái)通過(guò)本文給大家介紹php 使用mpdf實(shí)現(xiàn)指定字段配置字體樣式的方法,需要的朋友可以參考下2019-07-07php數(shù)組應(yīng)用之比較兩個(gè)時(shí)間的相減排序
因網(wǎng)站需要實(shí)現(xiàn)兩個(gè)時(shí)間段的所有小說(shuō)的收藏,點(diǎn)擊等操作,特把同事寫(xiě)的代碼收藏下,以后有需要研究2008-08-08Laravel統(tǒng)一錯(cuò)誤處理為JSON的方法介紹
這篇文章主要給大家介紹了關(guān)于Laravel統(tǒng)一錯(cuò)誤處理為JSON的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10ThinkPHP中Common/common.php文件常用函數(shù)功能分析
這篇文章主要介紹了ThinkPHP中Common/common.php文件常用函數(shù)功能,通過(guò)注釋的形式詳細(xì)分析了C方法、tag方法、B方法及autoload方法的功能與代碼原理,需要的朋友可以參考下2016-05-05微信小程序頁(yè)面向下滾動(dòng)時(shí)tab欄固定頁(yè)面頂部實(shí)例講解
這篇文章主要介紹了微信小程序頁(yè)面向下滾動(dòng)時(shí)tab欄固定頁(yè)面頂部實(shí)例講解,文中圖文實(shí)例講解的很透徹,有需要的同學(xué)可以參考下2021-03-03Symfony2針對(duì)輸入時(shí)間進(jìn)行查詢(xún)的方法分析
這篇文章主要介紹了Symfony2針對(duì)輸入時(shí)間進(jìn)行查詢(xún)的方法,結(jié)合實(shí)例形式分析了Symfony2針對(duì)mysql及MongoDB的輸入時(shí)間進(jìn)行轉(zhuǎn)換與查詢(xún)的相關(guān)操作技巧,需要的朋友可以參考下2017-06-06Yii1.1框架實(shí)現(xiàn)PHP極光推送消息通知功能
這篇文章主要介紹了Yii1.1框架實(shí)現(xiàn)PHP極光推送消息通知的相關(guān)資料,需要的朋友可以參考下2018-09-09Thinkphp5+PHPExcel實(shí)現(xiàn)批量上傳表格數(shù)據(jù)功能
這篇文章主要介紹了Thinkphp5+PHPExcel實(shí)現(xiàn)批量上傳表格數(shù)據(jù)功能,需要的朋友可以參考下2017-11-11