wr_1 여분필드에 임시저장 기능 활용하기

wr_1 여분필드에 임시저장 기능 활용하기

QA

wr_1 여분필드에 임시저장 기능 활용하기

본문

여분필드 wr_1에 임시저장 기능을 적용하기 위해 아래와 같이 했습니다.

아직 임시저장 테이블인 g5_autosave 에 wr_1 값이 저장도 되지 않고, 저장후 값을 불러오는 것도 안됩니다. (글쓰기에서 여분필드 wr_1에 글 저장하는 것은 잘 됩니다. 여분필드 wr_1 임시저장만 안됩니다.)

 

에디터는 smarteditor2를 이용했습니다. 글쓰기 폼에는 아래와 같이 적용을 했구요.

에디터로 글쓰는 곳

<?php echo editor_html("wr_1", $wr_1, $is_dhtml_editor); ?>

스크립트 추가한 곳   

    <?php echo get_editor_js("wr_1"); ?>
    <?php echo chk_editor_js("wr_1"); ?>

 

여분필드 wr_1에 임시저장 기능을 위해 아래와 같이 작업을 했습니다.

 

1) g5_autosave 테이블에 wr_1 필드 추가

 

2) js/autosave.js 파일을 아래와 같이 수정했습니다.


// 임시 저장하는 시간을 초단위로 설정한다.
var AUTOSAVE_INTERVAL = 60; // 초
// 글의 제목과 내용을 바뀐 부분이 있는지 비교하기 위하여 저장해 놓는 변수
var save_wr_subject = null;
var save_wr_content = null;
var save_wr_1 = null;
function autosave() {
    $("form#fwrite").each(function() {
        if(g5_editor != "") {
            if (g5_editor.indexOf("ckeditor4") != -1 && typeof(CKEDITOR.instances.wr_content)!="undefined") {
                this.wr_content.value = CKEDITOR.instances.wr_content.getData();
            } else if (g5_editor.indexOf("cheditor5") != -1 && typeof(ed_wr_content)!="undefined") {
                this.wr_content.value = ed_wr_content.outputBodyHTML();
            } else {
                if(typeof get_editor_wr_content == "function" || typeof get_editor_wr_1 == "function") {
                    this.wr_content.value = get_editor_wr_content();
                    this.wr_1.value = get_editor_wr_1();
                }
            }
        }
        // 변수에 저장해 놓은 값과 다를 경우에만 임시 저장함
        if (save_wr_subject != this.wr_subject.value || (save_wr_content != this.wr_content.value || save_wr_1 != this.wr_1.value)) {
            $.ajax({
                url: g5_bbs_url+"/ajax.autosave.php",
                data: {
                    "uid" : this.uid.value,
                    "subject": this.wr_subject.value,
                    "content": this.wr_content.value,
                    "wr_1": this.wr_1.value
                },
                type: "POST",
                success: function(data){
                    if (data) {
                        $("#autosave_count").html(data);
                    }
                }
            });
            save_wr_subject = this.wr_subject.value;
            save_wr_content = this.wr_content.value;
            save_wr_1 = this.wr_1.value;
        }
    });
}
$(function(){
    if (g5_is_member) {
        setInterval(autosave, AUTOSAVE_INTERVAL * 1000);
    }
    // 임시저장된 글목록을 가져옴
    $("#btn_autosave").click(function(){
        if ($("#autosave_pop").is(":hidden")) {
            $.get(g5_bbs_url+"/ajax.autosavelist.php", function(data){
                //alert(data);
                //console.log( "Data: " + data);
                $("#autosave_pop ul").empty();
                if ($(data).find("list").find("item").length > 0) {
                    $(data).find("list").find("item").each(function(i) {
                        var id = $(this).find("id").text();
                        var uid = $(this).find("uid").text();
                        var subject = $(this).find("subject").text();
                        var datetime = $(this).find("datetime").text();
                        $("#autosave_pop ul")
                            .append('<li><a href="#none" class="autosave_load">'+subject+'</a><span>'+datetime+' <button type="button" class="autosave_del">삭제</button></span></li>')
                            .find("li:eq("+i+")")
                            .data({ as_id: id, uid: uid });
                    });
                }
            }, "xml");
            $("#autosave_pop").show();
        } else {
            $("#autosave_pop").hide();
        }
    });
    // 임시저장된 글 제목과 내용을 가져와서 제목과 내용 입력박스에 노출해 줌
    $(document).on( "click", ".autosave_load", function(){
        var $li = $(this).parents("li");
        var as_id = $li.data("as_id");
        var as_uid = $li.data("uid");
        $("#fwrite input[name='uid']").val(as_uid);
        $.get(g5_bbs_url+"/ajax.autosaveload.php", {"as_id":as_id}, function(data){
            var subject = $(data).find("item").find("subject").text();
            var content = $(data).find("item").find("content").text();
            var wr_1 = $(data).find("item").find("wr_1").text();
            $("#wr_subject").val(subject);
            if(g5_editor != "") {
                if (g5_editor.indexOf("ckeditor4") != -1 && typeof(CKEDITOR.instances.wr_content)!="undefined") {
                    CKEDITOR.instances.wr_content.setData(content);
                } else if (g5_editor.indexOf("cheditor5") != -1 && typeof(ed_wr_content)!="undefined") {
                    ed_wr_content.putContents(content);
                } else {
                    if(typeof put_editor_wr_content == "function" || typeof put_editor_wr_1 == "function") {
                        put_editor_wr_content(content);
                        put_editor_wr_1(wr_1);
                    }
                }
            } else {
                $("#fwrite #wr_content").val(content);
            }
        }, "xml");
        $("#autosave_pop").hide();
    });
    $(document).on( "click", ".autosave_del", function(){
        var $li = $(this).parents("li");
        var as_id = $li.data("as_id");
        $.get(g5_bbs_url+"/ajax.autosavedel.php", {"as_id":as_id}, function(data){
            if (data == -1) {
                alert("임시 저장된글을 삭제중에 오류가 발생하였습니다.");
            } else {
                $("#autosave_count").html(data);
                $li.remove();
            }
        });
    });
    $(".autosave_close").click(function(){ $("#autosave_pop").hide(); });
});
 

 

3) bbs/ajax.autosave.php 를 아래와 같이 수정했습니다.

<?php
include_once('./_common.php');
 
if (!$is_member) die('0');
 
$uid     = isset($_REQUEST['uid']) ? preg_replace('/[^0-9]/', '', $_REQUEST['uid']) : 0;
$subject = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : '';
$content = isset($_REQUEST['content']) ? trim($_REQUEST['content']) : '';
$wr_1 = isset($_REQUEST['wr_1']) ? trim($_REQUEST['wr_1']) : '';
 
if ($subject && ($content || $wr_1)) {
    $sql = " select count(*) as cnt from {$g5['autosave_table']} where mb_id = '{$member['mb_id']}' and as_subject = '$subject' and ( as_content = '$content' or as_wr_1 = '$wr_1' ) ";
    $row = sql_fetch($sql);
    if (!$row['cnt']) {
        $sql = " insert into {$g5['autosave_table']} set mb_id = '{$member['mb_id']}', as_uid = '{$uid}', as_subject = '$subject', as_content = '$content', as_wr_1 = '$wr_1', as_datetime = '".G5_TIME_YMDHIS."' on duplicate key update as_subject = '$subject', as_content = '$content', as_wr_1 = '$wr_1', as_datetime = '".G5_TIME_YMDHIS."' ";
        $result = sql_query($sql, false);
 
        echo autosave_count($member['mb_id']);
    }
}

 

4) 마지막으로 plugin/editor/smarteditor2/autosave.editor.php 를 아래와 같이 수정했습니다.


function get_editor_wr_content()
{
    return oEditors.getById['wr_content'].getIR();;
}
function put_editor_wr_content(content)
{
    oEditors.getById["wr_content"].exec("SET_CONTENTS", [""]);
    //oEditors.getById["wr_content"].exec("SET_IR", [""]);
    oEditors.getById["wr_content"].exec("PASTE_HTML", [content]);
    return;
}
function get_editor_wr_1()
{
    return oEditors.getById['wr_1'].getIR();;
}
function put_editor_wr_1(wr_1)
{
    oEditors.getById["wr_1"].exec("SET_CONTENTS", [""]);
    //oEditors.getById["wr_1"].exec("SET_IR", [""]);
    oEditors.getById["wr_1"].exec("PASTE_HTML", [wr_1]);
    return;
}

 

 

이 질문에 댓글 쓰기 :

답변 1

다음 부분을 참고하셔서 적용해 보시는건 어떨까 합니다

autosave.js


// get_editor_wr_1 함수 수정
function get_editor_wr_1() {
    // 에디터가 smarteditor2인 경우
    if (typeof oEditors !== 'undefined' && typeof oEditors.getById === 'function' && oEditors.getById['wr_1']) {
        return oEditors.getById['wr_1'].getIR(); // smarteditor2의 경우 IR 값을 반환
    } else {
        return ''; // 에디터가 다른 경우 빈 문자열 반환
    }
}
// put_editor_wr_1 함수 수정
function put_editor_wr_1(wr_1) {
    // 에디터가 smarteditor2인 경우
    if (typeof oEditors !== 'undefined' && typeof oEditors.getById === 'function' && oEditors.getById['wr_1']) {
        oEditors.getById['wr_1'].exec("PASTE_HTML", [wr_1]); // smarteditor2의 경우 HTML 삽입
    }
}

 

ajax.autosave.php


include_once('./_common.php');
if (!$is_member) die('0');
$uid     = isset($_REQUEST['uid']) ? preg_replace('/[^0-9]/', '', $_REQUEST['uid']) : 0;
$subject = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : '';
$content = isset($_REQUEST['content']) ? trim($_REQUEST['content']) : '';
$wr_1    = isset($_REQUEST['wr_1']) ? trim($_REQUEST['wr_1']) : '';
if ($subject && ($content || $wr_1)) {
    $sql = "SELECT count(*) AS cnt FROM {$g5['autosave_table']} WHERE mb_id = '{$member['mb_id']}' AND as_subject = '$subject' AND (as_content = '$content' OR as_wr_1 = '$wr_1')";
    $row = sql_fetch($sql);
    if (!$row['cnt']) {
        $sql = "INSERT INTO {$g5['autosave_table']} SET mb_id = '{$member['mb_id']}', as_uid = '{$uid}', as_subject = '$subject', as_content = '$content', as_wr_1 = '$wr_1', as_datetime = '".G5_TIME_YMDHIS."' ON DUPLICATE KEY UPDATE as_subject = '$subject', as_content = '$content', as_wr_1 = '$wr_1', as_datetime = '".G5_TIME_YMDHIS."'";
        $result = sql_query($sql, false);
        echo autosave_count($member['mb_id']);
    }
}

답변 감사합니다.
알려주신 내용에서 autosave.js의 내용을 plugin/editor/smarteditor2/autosave.editor.php에 적용을 하고 ajax.autosave.php의 내용은 변동 사항이 없어 그대로 적용을 해 봤습니다.
변경 이후에도 wr_content 변화에는 임시저장이 되는데, 여분필드 값 변화에는 임시저장이 되지 않네요. 조금 더 연구해 봐야 겠어요 ;;

autosave.editor.php 수정:
smarteditor2의 설정 파일인 autosave.editor.php에도 wr_1 필드에 대한 임시 저장 기능을 추가해야 하지 않을까 생각합니다.

다음을 참고해 보세요


function get_editor_wr_1()
{
    return oEditors.getById['wr_1'].getIR(); // wr_1 필드에 대한 내용을 가져오는 함수
}

function put_editor_wr_1(wr_1)
{
    oEditors.getById["wr_1"].exec("PASTE_HTML", [wr_1]); // wr_1 필드에 대한 내용을 설정하는 함수
}


페이지의 HTML 구조 확인:
페이지의 HTML 구조를 확인하여 여분 필드인 wr_1이 올바르게 설정되어 있는지 확인,
wr_1 필드가 적절한 ID를 가지고 있어야 자바스크립트가 해당 필드를 찾을 수 있을 것으로 보입니다.

자바스크립트 코드 수정:
autosave.js 파일에서 wr_1 필드에 대한 처리를 확인
wr_content와 마찬가지로 wr_1 필드도 적절히 처리되어야 하지 않을까 합니다.

웹메이킹님의 말씀처럼 autosave.editor.php에도 적용이 되어 있습니다.
제가 설명드린 내용을 보시면 아래 내용들이 모두 적용되어 있습니다.
쓰기게시판
js/autosave.js 파일과 autosave 테이블에 wr_1 필드 추가
bbs/ajax.autosave.php
plugin/editor/smarteditor2/autosave.editor.php

답변을 작성하시기 전에 로그인 해주세요.
전체 109
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT