본문 바로가기
Sketcher

FullCalendar 와 DB 연동하기 -3 (이벤트 수정 & 삭제)

by 완두완두콩 2022. 2. 24.

FullCalendar 를 이용한 단순 기능 구현은 이번 챕터가 마지막일 것 같다!..

조회 , 생성을 해보니 어느정도 감이 잡혀서 수정과 삭제는 그리 오랜 시간이

걸리지는 않았다.

문제는 Controller 로직일뿐!..

제대로 된 로직이 아니라서 좀 엉망이지만

이번에도 단순히 수정 , 삭제 시에 데이터를 넘기고 DB 에 확인되는지만 확인했다.

이번 포스팅이 끝나면 이제 본격적으로 Controller 와 Query 작성을 하면 될 것 같다.

 

HTML


 

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  <script>
 
        var calendar = null;
        var initialLocaleCode = 'ko';
        var localeSelectorEl = document.getElementById('locale-selector');
 
            $(document).ready(function (){
 
                    var calendarEl = document.getElementById('calendar');
                    calendar = new FullCalendar.Calendar(calendarEl, {
                        initialDate: '2022-02-07',
                        initialView: 'timeGridWeek',
                        headerToolbar: {
                            left: 'prev,next today',
                            center: 'title',
                            right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
                        },
                        navLinks: true,
                        editable: true,
                        selectable: true,
                        droppable: true// this allows things to be dropped onto the calendar
 
                        // eventAdd: function () { // 이벤트가 추가되면 발생하는 이벤트
                        //     // console.log()
                        // },
 
                        /**
                         * 드래그로 이벤트 수정하기
                         */
                        eventDrop: function (info){
                            console.log(info);
                            if(confirm("'"+ info.event.title +"' 매니저의 일정을 수정하시겠습니까 ?")){
                            }
                            var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                            var obj = new Object();
 
                            obj.title = info.event._def.title;
                            obj.start = info.event._instance.range.start;
                            obj.end = info.event._instance.range.end;
                            events.push(obj);
 
                            console.log(events);
                            $(function deleteData() {
                                $.ajax({
                                    url: "/full-calendar/calendar-admin-update",
                                    method: "PATCH",
                                    dataType: "json",
                                    data: JSON.stringify(events),
                                    contentType: 'application/json',
                                })
                            })
                        },
 
                        /**
                         * 드래그로 이벤트 추가하기
                         */
                        select: function (arg) { // 캘린더에서 이벤트를 생성할 수 있다.
 
                            var title = prompt('일정을 입력해주세요.');
                            if (title) {
                                calendar.addEvent({
                                    title: title,
                                    start: arg.start,
                                    end: arg.end,
                                    allDay: arg.allDay,
                                })
                            }
 
                            var allEvent = calendar.getEvents(); // .getEvents() 함수로 모든 이벤트를 Array 형식으로 가져온다. (FullCalendar 기능 참조)
 
                            var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                            for (var i = 0; i < allEvent.length; i++) {
                                var obj = new Object();     // Json 을 담기 위해 Object 선언
                                // alert(allEvent[i]._def.title); // 이벤트 명칭 알람
                                obj.title = allEvent[i]._def.title; // 이벤트 명칭  ConsoleLog 로 확인 가능.
                                obj.start = allEvent[i]._instance.range.start; // 시작
                                obj.end = allEvent[i]._instance.range.end; // 끝
 
                                events.push(obj);
                            }
                            var jsondata = JSON.stringify(events);
                            console.log(jsondata);
                            // saveData(jsondata);
 
                            $(function saveData(jsondata) {
                                $.ajax({
                                    url: "/full-calendar/calendar-admin-update",
                                    method: "POST",
                                    dataType: "json",
                                    data: JSON.stringify(events),
                                    contentType: 'application/json',
                                })
                                    .done(function (result) {
                                        // alert(result);
                                    })
                                    .fail(function (request, status, error) {
                                         // alert("에러 발생" + error);
                                    });
                                calendar.unselect()
                            });
                        },
 
                        /**
                         * 이벤트 선택해서 삭제하기
                         */
                        eventClick: function (info){
                            if(confirm("'"+ info.event.title +"' 매니저의 일정을 삭제하시겠습니까 ?")){
                                // 확인 클릭 시
                                info.event.remove();
                            }
 
                            console.log(info.event);
                            var events = new Array(); // Json 데이터를 받기 위한 배열 선언
                            var obj = new Object();
                                obj.title = info.event._def.title;
                                obj.start = info.event._instance.range.start;
                                events.push(obj);
 
                            console.log(events);
                            $(function deleteData(){
                                $.ajax({
                                    url: "/full-calendar/calendar-admin-update",
                                    method: "DELETE",
                                    dataType: "json",
                                    data: JSON.stringify(events),
                                    contentType: 'application/json',
                                })
                            })
                        },
                        // eventRemove: function (obj) { // 이벤트가 삭제되면 발생하는 이벤트
                        //
                        // },
                        
                    });
                    calendar.render();
        });
 
 
 
 
    </script>
cs

 

우선 수정은 FullCalendar 에 있는 function 중 하나인 eventDrop 을 이용해서

작성하였다.

 

처음에는 eventDragStart 나 Stop 을 이용해서 해야하나 했는데 eventDrop 에 친절히

다른 시간 또는 다른 날짜로 이동했을 때 사용하는 것이라고 알려줘서

잠시 헤맨 뒤 , eventDrop 으로 설정하였다.

 

일정을 선택해서 끌어놓으면 , '매니저 이름' + 일정을 수정하겠냐는 팝업 생성 후,

확인을 누르면 생성에서와 똑같이 obj 객체에 집어넣고 데이터를 전송한다.

넘어온 데이터 중 , title(이름)은 그대로 두고 , 날짜만 수정할 것이기에

PUT 이 아닌 , PATCH 방식으로 데이터를 넘겼다.

 

 

삭제는 eventClick function 을 이용하여 구현했는데 , 해당 이벤트를 클릭하면

'매니저 이름' + 일정을 삭제하겠냐는 팝업 생성 후

확인을 누르면 obj 객체에 담아서 DELETE 로 method 로 보내준다.

 

 

Controller


 

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
  @DeleteMapping("/calendar-admin-update")
    @ResponseBody
    public String deleteEvent(@RequestBody List<Map<String, Object>> param){
 
        for (int i = 0; i < param.size(); i++) {
            String username = (String) param.get(i).get("title");
 
            User user = userService.findByUsername(username).get();
            managerAssignScheduleService.deleteByUser(user);
        }
 
 
        return "/full-calendar/calendar-admin-update";
    }
 
    @PatchMapping("/calendar-admin-update")
    @ResponseBody
    public String modifyEvent(@RequestBody List<Map<String, Object>> param){
 
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.KOREA);
 
        for (int i = 0; i < param.size(); i++) {
 
            String username = (String) param.get(i).get("title");
            String startDateString = (String) param.get(i).get("start");
            String endDateString = (String) param.get(i).get("end");
 
            LocalDateTime modifiedstartDate = LocalDateTime.parse(startDateString, dateTimeFormatter);
            LocalDateTime modifiedendDate = LocalDateTime.parse(endDateString, dateTimeFormatter);
 
            ScheduleDto scheduleDto = ScheduleDto.builder()
                    .scheduleDateTimeStart(modifiedstartDate)
                    .scheduleDateTimeEnd(modifiedendDate)
                    .build();
 
            Integer scheduleId = scheduleService.saveSchedule(scheduleDto);
            Schedule scheduleEntity = scheduleRepository.findById(scheduleId).get();
 
            ManagerAssignScheduleDto assignScheduleDto = ManagerAssignScheduleDto.builder()
                    .schedule(scheduleEntity)
                    .build();
 
            managerAssignScheduleService.saveManagerAssignSchedule(assignScheduleDto);
        }
        return "/full-calendar/calendar-admin-update";
        }
cs

 

컨트롤러 부분도 크게 달라진 부분은 없다!.. (수정해야하기에!..)

그냥 단순히 데이터를 넘겨 받아서 해당 데이터가 잘 가공돼서 들어가는지 확인하고

수정 삭제가 되는지 확인하기 위한 로직을 작성해서 테스트해봤다.

 

두콩 매니저 이벤트 생성
DB 에 저장
수정 팝업
ID 5 -> ID 6 날짜 변경 확인&nbsp;

기존 스케줄에서 바뀌어야하는데 새로 스케줄이 생성되는 것은 임시로 코드를 짠것이라!..

수정 예정!..

삭제 팝업
배정 스케줄 Table 에서 삭제 확인!

단순 기능 구현은 완료했으니 이제 Controller 와 Service & Repository 부분을 손보면 될 것 같다!

기능 구현하는데 너무 오랜 시간이 걸리면 어떡하지 걱정했는데

생각보다 금방 끝나서 다행이다..!

 

(각 로그인한 아이디로 본인 데이터만 조회 가능한 부분은 Spring Security 와 연동해서

작업해야 할 것 같으니 추후!..)

+ 캘린더 한글화 작업도 해야할 것 같다!

 

FullCalendar 다음 편!

https://dodokong.tistory.com/46?category=1262083

 

FullCalendar 와 DB 연동하기 -4 (생성 Controller & Service)

지금까지 말그대로 기능만 동작하도록 설정만 해놓았고, 데이터를 집어넣거나 빼거나 하면 무수한 오류 로그가 찍히고 있었다. 특히 생성 쪽은 for 문이 잘못 설정돼서 첫 이벤트는 괜찮으나 두

dodokong.tistory.com

 

댓글