YII view integrates the kindeditor extension method, yiikindeditor

Source: Internet
Author: User

YII view integrates the kindeditor extension method, yiikindeditor

This article describes how to integrate the YII view with kindeditor extension. We will share this with you for your reference. The details are as follows:

Kindeditor is preferred, and the version on YII is old, so you have to re-set the extension.
Create the KEditor folder under protected \ extensions to put files, put the kindeditor source file in the keSource, and then create three types of KEditor, KEditorManage, and KEditorUpload. KEditor is an extended main file, KEditorManage is used to browse server files, and KEditorUpload is used to receive uploaded files as an example,

KEditor code

<? Phpclass KEditor extends CWidget {/** attributes of the TEXTAREA input box to ensure the style of the text box when the js call KE fails. */Public $ textareaOptions = array ();/** editor attribute set. */Public $ properties = array ();/** name of the TEXTAREA input box, which must be set. * Data Type: String */public $ name;/** TEXTAREA id, which can be empty */public $ id; public $ model; public $ baseUrl; public static function getUploadPath () {$ dir = dirname (_ FILE __). DIRECTORY_SEPARATOR. 'source'; 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. 'source'; 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. 'source'; $ 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 = <EOFKindEditor. 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 () {// attributes that can be obtained $ allowParams = array ('rows ', 'cols', 'style'); // prepare the returned attribute array $ 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 ', 'threceive', 'langtype', 'designmode', 'fullscreenmode', 'basepath', 'themespath', 'ininspath', 'langpath ', 'minchangesize', 'urltype', 'newlinetag', 'pasttype', 'dialogaligntype', 'shadowmode', 'usecontextcall', 'synctype ', 'inputchar', 'csspath ', 'cssdata', 'bodyclass', 'colortable', 'aftercreate', 'afterchang', 'aftertab', 'afterfo', 'afterblur', 'afterupload', 'uploadjson ', 'filemanagerjson', 'authorization', 'allowimageupload', 'allowupload', 'allowmediapload', 'allowfileupload', 'allowfilmanager', 'authorization', 'imagetabindex ', 'formatuploadurl ', 'fullscreenshortcut ', 'extrafileuploadparams',); // prepare the returned attribute array $ params = array (); foreach ($ properties_key as $ key) {if (isset ($ this-> properties [$ key]) $ params [$ key] = $ this-> properties [$ key];} return $ params ;}}

KEditorManage code

<? Phpclass KEditorManage extends CAction {public function run () {Yii: import ('ext. KEditor. KEditor '); $ root_path = KEditor: getUploadPath (). '/'; $ root_url = KEditor: getUploadUrl (). '/'; // image extension $ ext_arr = array ('gif', 'jpg ', 'jpeg', 'png ', 'bmp '); // directory name $ 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) ;}}// set the path and URL if (empty ($ _ GET ['path']) according to the path parameter) {$ 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); // sorting form, name or size or type $ order = empty ($ _ GET ['order'])? 'Name': strtolower ($ _ GET ['order']); // not allowed .. move to the upper-level directory if (preg_match ('/\. \. /', $ current_path) {echo 'Access is not allowed. '; exit;} // The last character is not/if (! Preg_match ('/\/$/', $ current_path) {echo 'parameter is not valid. '; exit;} // The directory does not exist or is not the directory if (! File_exists ($ current_path) |! Is_dir ($ current_path) {echo 'Directory does not exist. '; exit;} // retrieve the file information through the directory $ 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; // whether the folder $ file_list [$ I] ['has _ file'] = (count (scandir ($ file-> getPath ()> 2 ); // whether the folder contains the file $ file_list [$ I] ['filesize'] = 0; // the file size $ file_li St [$ I] ['is _ photo '] = false; // whether the image is $ file_list [$ I] ['filetype'] = ''; // file category, use the extension to determine} 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 name, including the extension $ file_list [$ I] ['datetime'] = date ('Y-m-d H: i: s', $ file-> getMTime (); $ I ++;} usort ($ file_list, array ($ this, 'cmp _ func ')); $ result = array (); // The upper-level directory relative to the root directory $ result ['moveup _ dir_path '] = $ moveup_dir_path; // relative to the current directory of the root directory $ result ['current _ dir_path '] = $ current_dir_path; // the URL of the current directory $ result ['current _ url'] = $ current_url; // number of files $ result ['total _ count'] = count ($ file_lis T); // file list array $ result ['file _ list'] = $ file_list; // output the JSON string header ('content-type: application/json; charset = UTF-8 '); echo CJSON: encode ($ result); exit;} // sort 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 code

<? Phpclass 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', 'av', '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' => 'directory name is incorrect. '); Exit ;}$ originalurl = ''; $ filename =''; $ date = date ('ymmd'); $ 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' => 'the size of the uploaded file exceeds the limit. '); Exit;} // new file name $ filename = date ("YmdHis "). '_'. rand (10000,999 99); $ ext = $ upload_image-> extensionName; if (in_array ($ ext, $ ext_arr [$ dir]) === false) {echo CJSON :: encode (array ('error' => 1, 'message' => "the upload file extension is not allowed. \ N only supports the ". implode (',', $ ext_arr [$ dir]). 'format. '); 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' => 'unknown error '));}}}

Configure the config/main. php file and set the storage location of the uploaded file

'Params' => array (// this is used in contact page 'adminmail' => 'webmaster @ example.com ', 'uploadpath' =>'/upload ', // Add this sentence. upload is the name of the folder where the file is stored and defined by yourself. It is placed in the upload folder of the root directory.

Set the action for receiving and browsing server files

Public function actions () {return array (// Add the following two sentences in return array under actions, add 'upload' => array ('class' => 'application. extensions. KEditor. KEditorUpload '), 'managejson' => array ('class' => 'application. extensions. KEditor. KEditorManage '),);}

Use in the view

<? Php $ this-> widget ('ext. KEditor. KEditor ', array ('model' => $ model, // input form model 'name' => 'content ', // set the name 'properties' => array (// set the action 'uploadjson' => '/admin/default/upload' for receiving file uploads ', // set the action for browsing the Server File. These two are the 'filemanagerjson' => '/admin/default/managejson' configured in/admin/default ', 'newlineag' => 'br ', 'allowfilemanager' => true, // Add js before passing values: To mark these js codes as 'aftercreate' => "js: function () {K ('# ChapterForm_all_len ') . Val (this. count (); K ('# ChapterForm_word_len '). val (this. count ('text');} ", 'afterchang' =>" js: function () {K ('# ChapterForm_all_len '). val (this. count (); K ('# ChapterForm_word_len '). val (this. count ('text');} ",), 'texteaoptions' => array ('style' => 'width: 98%; height: 400px; ',);?>

TextareaOptions is used to set the size and style of textarea. It only supports rows, cols, and style.
Properties is the same as setting kindeditor in js. The above settings are the same as those set in js below. You can set all the original items in 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'));  }});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.