前回、Google Calendar Apiからイベントを同期してfullcalendarに
反映させるところまでを書きました。
今回はイベントの登録の方法を書きたいと思います。
クリックして登録するまでの処理の流れ
1.空いている時間をクリックするとタイトルの入力画面がモーダルで出る
2.タイトルを入力して『OK』ボタンを押す
3.GoogleCalendarとfullcalendar両方に反映させる
大きく分けてこの3つになります。
1の処理
fullcalendarの空いている時間をクリックした時の処理は
select:
を使います。
ちなみに他のクリックイベントは
月のカレンダーで空いている日に終日予定を入れる場合 => dayClick
イベントをクリックした場合(更新とか削除の時に使用)=> eventClick
にそれぞれ処理を書きます。
今回は新しく時間単位でイベントを登録してみます。
selectイベントの処理
select: function(start, end, allDay) {
var title = prompt('タイトルを入力してください');
if (!allDay) {
$('#calendar').fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
color: 'pink',
allDay: false
});
}
else
{
$('#calendar').fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
color: 'pink',
allDay: allDay
});
};
$('#calendar').fullCalendar('unselect');
$.ajax({
url: '/api/gcals/create_event_self',
type: 'POST',
dataType: 'json',
data: {
title: title,
start: start,
end: end
},
})
},
終日をクリックしたかどうかで条件分岐しています。
fullcalendarにイベントを表示させるのはrenderEventです。
まずはrenderEventでクリックした時間帯の色を変えて分かり易くします。
そのあとGooogleCalendarApiにAjaxで投げてGoogleCalendarにも
反映させます。
2、3の処理
def create_event_self
event = [
current_user[:email],
params[:title],
params[:start],
params[:end]
]
#UserのGmailが必要になるのでcurrent_user[:email]で渡す
new_event = Gcal.new.insert_event(event)
end
def insert_event(event) #UserのGmailを受け取るので引数が必要
email = event[0]
start_time = DateTime.parse(event[2])
end_time = DateTime.parse(event[3])
event_resorces = {
'summary' => event[1],#fullcalendarのtitle
'start' => {
'dateTime' => start_time
},
'end' => {
'dateTime' => end_time
},
}
result = @client.execute(:api_method => @service.events.insert,
:parameters => {'calendarId' => email },
:body => JSON.dump(event_resorces),
:headers => {'Content-Type' => 'application/json'})
end
post 'gcals/create_event_self' => 'gcals#create_event_self'
これで好きな時間帯にイベントを登録できるようになりました!
GoogleCalendarにも反映されていると思いますので確認してみてください。
次回は更新、削除を書いていきます。
なお初心者のため、もっとこう書いた方が良いよとかありましたら
ご指摘いただけると嬉しいです。