게시판
      
상위분류 : 잡필방 중위분류 : 서류가방 하위분류 : 전산과 컴퓨터
작성자 : 문시형 작성일 : 2017-08-09 조회수 : 7,539
제 목 : 위지윅에디터 ckeditor 사용하기(CodeIgniter에 적용하기)

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 파일을 수정해야 합니다.

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

function CheckAuthentication()

{

    return true;

}

//true로 수정

//권한체크용으로 만들어진 함수인데 수정하지 않으면 파일업로드가 안됩니다.

 

$baseUrl '/data/upload';

//업로드된 파일이 저장될 디렉토리

//upload 디렉토리 하위에 파일형식에 따라서 이미지(images), 파일(files), 플래시(flash) 디렉토리가 자동생성됩니다.

//쓰기권한 필수

 

$config['ResourceType'][] = Array(

        'name' => 'Images',

        'url' => $baseUrl 'ck_images',

        'directory' => $baseDir 'ck_images',

        'maxSize' => '2M',

        'allowedExtensions' => 'bmp,gif,jpeg,jpg,png',

        'deniedExtensions' => '');

// maxSize가 처음에는 0으로 되어있는데 제한사이즈로 수정

// $config['ResourceType'][] 3군데 모두 수정

 

// 그외에는 각자 입맛(?)에 맞게 수정하시면 됩니다.

3. ckeditor_helper.php 파일을 생성합니다.(헬퍼 디렉토리)

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

<?php

if(!defined('BASEPATH')) exit('No direct script access allowed');

 

function form_ckeditor($data)

{

    //툴바 선택사용

    switch($data['toolbar']){

        case ('reply'):

        $tool_bar = '

            [

                ["Font","FontSize"], ["TextColor","BGColor"],

                ["Bold","Italic","Underline"],

                ["JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock"],

                ["Link","Unlink"],

                ["Image","Flash","Table","HorizontalRule","Smiley","SpecialChar"],

                ["Preview","Source","Maximize"]

            ]

        ';

        break;

        case ('basic'):

        $tool_bar = '

            [

                ["Source","-","Preview"],

                ["Bold","Italic","Underline"],

                ["Link","Unlink"]

            ]

        ';

        break;

        //디폴트는 FUll입니다.

        default:

        $tool_bar = '

            [

                ["Source","-","Save","NewPage","Preview","-","Templates"],

                ["Cut","Copy","Paste","PasteText","PasteFromWord","-","Print""SpellChecker""Scayt"],

                ["Undo","Redo","-","Find","Replace","-","SelectAll","RemoveFormat"],

                ["Form""Checkbox""Radio""TextField""Textarea""Select""Button""ImageButton""HiddenField"],

                "/",

                ["Bold","Italic","Underline","Strike","-","Subscript","Superscript"],

                ["NumberedList","BulletedList","-","Outdent","Indent","Blockquote"],

                ["JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock"],

                ["Link","Unlink","Anchor"],

                ["Image","Flash","Table","HorizontalRule","Smiley","SpecialChar","PageBreak"],

                "/",

                ["Styles","Format","Font","FontSize"],

                ["TextColor","BGColor"],

                ["Maximize""ShowBlocks","-","About"]

            ]

        ';

        break;

    }

 

 

    $data['language'] = isset($data['language']) ? $data['language'] : 'ko';

 

    $size    = isset($data['width']) ? 'width: "'.$data['width'].'", ' '';

    $size  .= isset($data['height']) ? 'height: "'.$data['height'].'", ' '';

 

    $options '{'.

            $size.

            'language: "'.$data['language'].'",

            //각종 설정값 (자세한내용은 ckeditor 레퍼런스참고)

            startupOutlineBlocks: false,

            entities: false,

            entities_latin: false,

            entities_greek: false,

            forcePasteAsPlainText: false,

 

//파일업로드 프로그램의 주소입니다.

//ckfinder의 주소를 적으면 됩니다.

//사용자 업로더를 사용한다면 그 주소를 써주면 됩니다.            filebrowserUploadUrl : "/include/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files",

            filebrowserImageUploadUrl : "/include/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images",

            filebrowserFlashUploadUrl : "/include/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash",

 

            toolbar : '.$tool_bar.'

 

        }';

    //ckeditor 선언부

    return

    // fix: move to <HEAD...

    '<script type="text/javascript" src="'.INCLUDE_DIR.'/ckeditor/ckeditor.js"></script>' .

 

    // put the CKEditor

     '<script type="text/javascript">CKEDITOR.replace("'.$data['id'].'", ' $options ');</script>';

}

?>

4. 사용
- 컨트롤러

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?php

 

class Test extends Controller {

 

    function Test()

    {

        parent::Controller();

    }

 

    function index() {

        //헬퍼 선언

        $this->load->helper('ckeditor');

        if (@$_POST['mode'] == 'edit') {

            $data['textarea_value'] = stripcslashes($_POST['textarea_id']);

        else {

            $data['textarea_value'] = '';

        }

        $this->load->view('admin/test'$data);

    }

}

?>

- 뷰

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

<input onclick="ExecuteCommand('image');" type="button" value="파일업로드"/>

<form action="" method="post">

<input type="hidden" name="mode" value="edit" />

<!--

textarea name과 하단 form_ckeditor의 id변수 동일해야

textarea를 ckeditor로 대체해줍니다.

기존값이 있다면 <textarea></textarea>사이에 선언

-->

<textarea name="textarea_id"><?=(@$textarea_value)?@$textarea_value:''?></textarea>

<input type="submit" value="등록" />

</form>

<?

//툴바, textarea name, 에디터 폭, 에디터 높이

//툴바를 빈칸으로 하면 FULL 툴바가 나옵니다.

//현재 선언해놓은 것은 reply와 basic인데 입맛에 맞게 선언하여 사용하면 됩니다.

echo form_ckeditor(array(

    'toolbar'        => 'reply',

    'id'              => 'textarea_id',

    'width'           => '500',

    'height'          => '300'

));

?>

<!--

툴바의 버튼을 외부로 뺄수도 있습니다.

맨 윗라인의 이미지 업로더를 버튼을 에디터 외부에 위치시키는 팁입니다.

-->

<script>

function ExecuteCommand( commandName )

{

    // Get the editor instance that we want to interact with.

    var oEditor = CKEDITOR.instances.textarea_id ;

 

    // Check the active editing mode.

    if (oEditor.mode == 'wysiwyg' )

    {

        // Execute the command.

        oEditor.execCommand( commandName ) ;

    }

    else

        alert( 'You must be on WYSIWYG mode!' ) ;

}

</script>

5. 끝
위 내용 데모는 http://hbuilder.kiissoft.com/admin/test 에서 보실 수 있습니다.

| | 목록으로