위지윅에디터 ckeditor 사용하기(CodeIgniter에 적용하기)

from 웅파/팁앤텍 2010/01/29 16:39

http://code (새 창으로 열기)igniter-kr.org codeigniter 한국사용자포럼에 정리해서 올렸던 내용을 제 블로그로 꺼꾸로 가져옵니다.
ckeditor 3.X버전을 codeigniter에서 사용할 수 있도록 수정한 내용입니다.

원본 http://codeigniter-kr.org/source/view/322/page/1 (새 창으로 열기)

fckeditor가 2.X대 버전으로 끝나고 3.X버전으로 오면서 ckeditor로 바뀌면서
상당히 많은 변화가 있었네요.
기능들을 코어와 플러그인으로 분리, 엄청난(?) 로딩속도 향상(http://hbuilder.kiissoft.com/admin/test), ajax 적용용이 등등..

파일, 이미지 업로드를 사용하기 위해서는(업로더가 2.X버전에서는 fckeditor안에 포함되어 있었음)
ckfinder도 같이 설치를 해야합니다.

ci forum에서 검색해보니 ckeditor용 헬퍼를 만들어놓은게 있어서 적용하여 사용중에 툴바선택할 수 있는
부분을 추가했습니다. (fckeditor는 라이브러리로 만들어 사용)

사용하기 위해서 ckeditor(http://ckeditor.com/download)와 ckfinder(http://ckfinder.com/download)(이미지 업로더를 따로 만든다면 필요가 없습니다)를 다운로드합니다.

1. 압축을 풀고 (저는 include 디렉토리 아래에 풀었습니다.)
   include - ckeditor
                 - ckfinder

2. 설정을 합니다.
 - ckeditor는 config.js 파일이 설정파일인데 헬퍼에서 설정을 해서 따로 설정할 것이 없습니다.
 - ckfinder는 config.php 파일을 수정해야 합니다.
 
01.function CheckAuthentication()
02.{
03.    return true;
04.}
05.//true로 수정
06.//권한체크용으로 만들어진 함수인데 수정하지 않으면 파일업로드가 안됩니다.
07.  
08.$baseUrl = '/data/upload'
09.//업로드된 파일이 저장될 디렉토리
10.//upload 디렉토리 하위에 파일형식에 따라서 이미지(images), 파일(files), 플래시(flash) 디렉토리가 자동생성됩니다.
11.//쓰기권한 필수
12.  
13.$config['ResourceType'][] = Array(
14.        'name' => 'Images',
15.        'url' => $baseUrl . 'ck_images',
16.        'directory' => $baseDir . 'ck_images',
17.        'maxSize' => '2M',
18.        'allowedExtensions' => 'bmp,gif,jpeg,jpg,png',
19.        'deniedExtensions' => '');
20.// maxSize가 처음에는 0으로 되어있는데 제한사이즈로 수정
21.// $config['ResourceType'][] 3군데 모두 수정
22.  
23.// 그외에는 각자 입맛(?)에 맞게 수정하시면 됩니다.
3. ckeditor_helper.php 파일을 생성합니다.(헬퍼 디렉토리)
 
01.<?php
02.if(!defined('BASEPATH')) exit('No direct script access allowed');
03.  
04.function form_ckeditor($data)
05.{
06.    //툴바 선택사용
07.    switch($data['toolbar']){
08.        case ('reply'):
09.        $tool_bar = '
10.            [
11.                ["Font","FontSize"], ["TextColor","BGColor"],
12.                ["Bold","Italic","Underline"],
13.                ["JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock"],
14.                ["Link","Unlink"],
15.                ["Image","Flash","Table","HorizontalRule","Smiley","SpecialChar"],
16.                ["Preview","Source","Maximize"]
17.            ]
18.        ';
19.        break;
20.        case ('basic'):
21.        $tool_bar = '
22.            [
23.                ["Source","-","Preview"],
24.                ["Bold","Italic","Underline"],
25.                ["Link","Unlink"]
26.            ]
27.        ';
28.        break;
29.        //디폴트는 FUll입니다.
30.        default:
31.        $tool_bar = '
32.            [
33.                ["Source","-","Save","NewPage","Preview","-","Templates"],
34.                ["Cut","Copy","Paste","PasteText","PasteFromWord","-","Print", "SpellChecker", "Scayt"],
35.                ["Undo","Redo","-","Find","Replace","-","SelectAll","RemoveFormat"],
36.                ["Form", "Checkbox", "Radio", "TextField", "Textarea", "Select", "Button", "ImageButton", "HiddenField"],
37.                "/",
38.                ["Bold","Italic","Underline","Strike","-","Subscript","Superscript"],
39.                ["NumberedList","BulletedList","-","Outdent","Indent","Blockquote"],
40.                ["JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock"],
41.                ["Link","Unlink","Anchor"],
42.                ["Image","Flash","Table","HorizontalRule","Smiley","SpecialChar","PageBreak"],
43.                "/",
44.                ["Styles","Format","Font","FontSize"],
45.                ["TextColor","BGColor"],
46.                ["Maximize", "ShowBlocks","-","About"]
47.            ]
48.        ';
49.        break;
50.    }
51.  
52.  
53.    $data['language'] = isset($data['language']) ? $data['language'] : 'ko';
54.  
55.    $size    = isset($data['width']) ? 'width: "'.$data['width'].'", ' : '';
56.    $size  .= isset($data['height']) ? 'height: "'.$data['height'].'", ' : '';
57.  
58.    $options = '{'.
59.            $size.
60.            'language: "'.$data['language'].'",
61.            //각종 설정값 (자세한내용은 ckeditor 레퍼런스참고)
62.            startupOutlineBlocks: false,
63.            entities: false,
64.            entities_latin: false,
65.            entities_greek: false,
66.            forcePasteAsPlainText: false,
67.  
68.//파일업로드 프로그램의 주소입니다.
69.//ckfinder의 주소를 적으면 됩니다. 
70.//사용자 업로더를 사용한다면 그 주소를 써주면 됩니다.            filebrowserUploadUrl : "/include/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files",
71.            filebrowserImageUploadUrl : "/include/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images",
72.            filebrowserFlashUploadUrl : "/include/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash",
73.  
74.            toolbar : '.$tool_bar.'
75.  
76.        }';
77.    //ckeditor 선언부
78.    return
79.    // fix: move to <HEAD...
80.    '<script type="text/javascript" src="'.INCLUDE_DIR.'/ckeditor/ckeditor.js"></script>' .
81.  
82.    // put the CKEditor
83.     '<script type="text/javascript">CKEDITOR.replace("'.$data['id'].'", ' . $options . ');</script>';
84.}
85.?>

4. 사용
- 컨트롤러
 
01.<?php
02.  
03.class Test extends Controller {
04.  
05.    function Test()
06.    {
07.        parent::Controller();
08.    }
09.  
10.    function index() {
11.        //헬퍼 선언
12.        $this->load->helper('ckeditor');
13.        if (@$_POST['mode'] == 'edit') {
14.            $data['textarea_value'] = stripcslashes($_POST['textarea_id']);
15.        } else {
16.            $data['textarea_value'] = '';
17.        }
18.        $this->load->view('admin/test', $data);
19.    }
20.}
21.?>

- 뷰
 
01.<input onclick="ExecuteCommand('image');" type="button" value="파일업로드"/>
02.<form action="" method="post">
03.<input type="hidden" name="mode" value="edit" />
04.<!--
05.textarea name과 하단 form_ckeditor의 id변수 동일해야
06.textarea를 ckeditor로 대체해줍니다.
07.기존값이 있다면 <textarea></textarea>사이에 선언
08.-->
09.<textarea name="textarea_id"><?=(@$textarea_value)?@$textarea_value:''?></textarea>
10.<input type="submit" value="등록" />
11.</form>
12.<?
13.//툴바, textarea name, 에디터 폭, 에디터 높이
14.//툴바를 빈칸으로 하면 FULL 툴바가 나옵니다.
15.//현재 선언해놓은 것은 reply와 basic인데 입맛에 맞게 선언하여 사용하면 됩니다.
16.echo form_ckeditor(array(
17.    'toolbar'        => 'reply',
18.    'id'              => 'textarea_id',
19.    'width'           => '500',
20.    'height'          => '300'
21.));
22.?>
23.<!--
24.툴바의 버튼을 외부로 뺄수도 있습니다. 
25.맨 윗라인의 이미지 업로더를 버튼을 에디터 외부에 위치시키는 팁입니다.
26.-->
27.<script>
28.function ExecuteCommand( commandName )
29.{
30.    // Get the editor instance that we want to interact with.
31.    var oEditor = CKEDITOR.instances.textarea_id ;
32.  
33.    // Check the active editing mode.
34.    if (oEditor.mode == 'wysiwyg' )
35.    {
36.        // Execute the command.
37.        oEditor.execCommand( commandName ) ;
38.    }
39.    else
40.        alert( 'You must be on WYSIWYG mode!' ) ;
41.}
42.</script>

5. 끝
위 내용 데모는 http://hbuilder.kiissoft.com/admin/test 에서 보실 수 있습니다.
크리에이티브 커먼즈 라이센스
Creative Commons License
2010/01/29 16:39 2010/01/29 16:39

Trackback Address :: http://jblove.net/b12/trackback/1550