How to register an event using addEventSource in fullCalendar? - javascript

When I click on the dayClick, I want to add an event to the clicked date.
I have the following JS code:
$('#calendar').fullCalendar({
header: {
center: "title", // 센터에는 타이틀 명이 오고
left: "prev", // 왼쪽에는 < 버튼이 오고
right: "next" // 오른쪽에는 > 버튼이 오게됌
},
lang: 'ko', // 달력 한글 설정
editable: true, // 달력의 이벤트를 수정할 수 있는지 여부를 결정
dayClick: function(date, allDay, view) // 일 클릭시 발생
{
var dateFormat = date.format('YYYY-MM-DD');
if (confirm('Do you want to register as closed?')) {
// Register event
} else {
alert('You Click No');
}
}
});
//Register event this part, how do I add the code?
I've been very careful with the "select" feature, but the functionality I want to implement is simple, so I prefer using "addEventSource" rather than "select".
But I am a beginner of jquery and javascript, so I do not know how to write it.
Please guide me on how to write code.
And I would really appreciate it if you could give me a link to a site or question I could refer to.
(Oh, note that all title values for events to be registered are "closed")

Set the following options for fullcalendar. See select demo.
selectable: true,
selectHelper: true,
select: function (start, end, jsEvent, view) {
var title = 'Some Event';
var eventData = {
title: title,
start: start,
end: end
};
if (confirm('Do you want to register as closed?')) {
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
} else {
alert('You Click No');
}
$('#calendar').fullCalendar('unselect');
},
Setting the select callback allows the use to click and drag to select multiple dates and set an event.
To allow only single day events, restrict the user to only clicks by setting dayClick option for fullcalendar instead.
dayClick: function (start, end, jsEvent, view) {
var title = 'Some Event';
var eventData = {
title: title,
start: start,
};
if (confirm('Do you want to register as closed?')) {
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
} else {
alert('You Click No');
}
$('#calendar').fullCalendar('unselect');
},

Related

Adding a button to each cell in fullcalendar to allow user to add an event using jQuery

I have been using jQuery along with fullcalendar to create a calendar that displays events from a database using php and MYSQL.
The calendar looks like this.
The events are shown in red. I would like to be able to add a button in each of the cells that do not have an event to allow the user to be able to add one.
Here is the code I have tried
viewRender: function (view) {
$(".fc-content").append('<button>Add</button>')
}
my full code.
$(document).ready(() => {
const calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
defaultTimedEventDuration: '01:00',
allDaySlot: false,
scrollTime: '09:00',
businessHours: {
dow: [ 2, 3, 4, 5, 6 ],
start: '09:00',
end: '17:30'
},
//viewRender: function (view) {
// $(".fc-content").append('<button>Book</button>');
// },
long: /^en-/.test(navigator.language) ? 'en' : 'zh-cn',
eventOverlap: (stillEvent, movingEvent) => {
return true;
},
events:
<?php echo $json;?>
//'2018-12-12T15:00+08:00'
//},
//{
//title: '',
//start: '' //'2018-12-12T12:00+08.00'
,
eventColor: '#FF0000',
edittable: true,
selectable: true,
selectHelper: true,
select: (start, end) => {
const duration = (end - start) / 1000;
if(duration == 1800){
// set default duration to 1 hr.
end = start.add(30, 'mins');
return
calendar.fullCalendar('select', start, end);
}
let eventData;
if (title && title.trim()) {
eventData = {
title: title,
start: start,
end: end
};
calendar.fullCalendar('renderEvent', eventData);
}
calendar.fullCalendar('unselect');
},
eventRender: (event, element) => {
const start = moment(event.start).fromNow();
element.attr('title', start);
},
loading: () => {}
});
});
Ok first off, unless the button is required from UI/UX perspective, you can skip adding the button and just work with fullCalendars built-in method/events.
example (skipping irrelevant options):
fullCalendar({
...
editable: true,
selectable: true, // makes each day selectable
select: function (start, end) {
// in this select callback you are given the start and end dates of the user's selection
// when a user selects any cells this will fire and you can do stuff in here
// fullcalendar will always give 2 dates as callback, even if the user only selected 1
// date, the 'end' will correspond to the next day actually...
events: [{event1},{event2},{event3}], // use this to initialize the events already //existing
eventClick: function (event) {
// this is the handler that will run when the user clicks on an event, not a day! an //event on a day
}
}
})
I hope this helps, you can always read more on the docs
You do not need button ..
you can do it in function eventClick this trigger in click on any day
$('#calendar').fullcalendar({
eventClick : function(xEvent, jsEvent, view){ hus_eventClick(xEvent, jsEvent, view);} ,
});
and in function show dialog box to add event ..
https://fullcalendar.io/docs/dayClick

How to prevent duplication against dayClick?

Before questioning, I reveal that I am a beginner.
I'm using fullCalendar for the first time.
When I clicked on the date, I made the event registration.
var calendar = $('#calendar').fullCalendar
({
dayClick: function (date, allDay, jsEvent, view)
{
$('#calendar').fullCalendar('renderEvent',
{
title : '휴진',
allDay : true,
start: date, //specify start date
stick : true,
backgroundColor: '#fe4978'
});
}
});
This code allows duplication in event registration.
Once an event is registered for a specific date, I would like to prevent the event from being registered thereafter.
I have seen docs related to removeEvent, but I do not know how to write the code.
I would really appreciate it if you could give me a guide.
This could help you #won.
$('#calendar').fullCalendar({
dayClick: function(date, allDay, jsEvent, view) {
$('#calendar').fullCalendar('clientEvents', function(event) {
if(event.start <= date && event.end >= date) {
return true;
}
return false;
});
}
});
Updated:
Add a function before you store the selected event into the object.
function IsDateHasEvent(date) {
var allEvents = [];
// add your calendar events into the array.
allEvents = $('#calendar').fullCalendar('clientEvents');
var event = $.grep(allEvents, function (v) {
return +v.start === +date;
});
return event.length > 0;
}
and change your code as follows.
dayClick: function (date, allDay, jsEvent, view) {
if (!IsDateHasEvent(date)) {
// No previous event on this date.
selectedDate = date;
eventData = {
title: title,
start: start,
stick : true,
backgroundColor: '#fe4978',
overlap: false,
};
$('#calendar').fullCalendar('renderEvent', eventData, true);
// add new appointment code.
//$("#divAddNewAppointment").dialog("open");
}
else {
//$('<%= "#" + lblMessage.ClientID%>').html(" your error msg");
$('#calendar').fullCalendar('unselect');
$("#divMessage").dialog("open");
}
}

Fullcalendar - conditional rendering one event

INTRO
Hey, I'm writing page using jquery fullcalendar to display events from my Salesforce org. I'm struggling to implement conditional rendering of events which happen to be on the exact same time in calendar, what looks like this:
SPECIFICATION
The green on the left represent working hours of dentist and after clicking one of them user is redirected to fill out the form, after that there is created event which is marked as red one.
PROBLEM
I would like to implement function or whatever makes sense to remove, or overlap the events on the left side (green or red). Is there any specific concept I should be using ? Thanks for your time.
Here is a code which I wrote :
function getEventData(dentistId) {
alert(dentistId);
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.CalendarController.eventData}', dentistId,
function(result, event){
if (event.status) {
evt = JSON.parse(result);
console.log(evt);
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listDay',
},
eventClick: function (calEvent, jsEvent, view) {
if(calEvent.editable === true) {
var start = moment(calEvent.start).format('YYYY-MM-DD HH:mm:ss');
var end = moment(calEvent.end).format('YYYY-MM-DD HH:mm:ss');
jQuery('[id$=startStringField]').val(start);
jQuery('[id$=endStringField]').val(end);
passToController();
} else {
return false;
}
},
eventOverlap: false,
defaultDate: $('#calendar').fullCalendar('today'),
navLinks: true,
events: evt,
eventRender: function(event, element) {
element.qtip({
content: event.description
});
},
textColor: 'white',
height:650,
})
} else if (event.type === 'exception') {
console.log(event.message);
} else {
console.log(event.message);
}
},
{escape: false}
);
}
The result is a string in json format which represent array of events to be displayed which are then parsed:
Json which is parsed to array of objects

Disable dragging while selecting time when creating an event

I am using FullCalender to display calendar and enable users to create events in the calendar, with dynamic duration that can be selected from a dropdown.
When a user only CLICKs on the calendar, I get the desired result that is only the desired duration is selected. which is CORRECT.
But the issue is when a user CLICKs and continues to DRAG to select a time range. I don't want the user to be able to select more than specified duration i.e. say 5mins. Only CLICKing selects 5mins and that is perfectly working fine. Only issue is while DRAGing with CLICKing.
I have tried various options available in the FullCalendar docs, but nothing helped.
Any help is appreciated. Thanks in Advance.
Current integration is in the below link to the Fiddle
https://jsfiddle.net/4h28Lt81/
Jquery is as below:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaDay',
slotDuration: '00:05:00',
slotEventOverlap: false,
defaultDate: '2016-06-12',
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true);
}
$('#calendar').fullCalendar('unselect');
},
editable: true,
eventLimit: true, // allow "more" link when too many events
loading: function(bool) {
$('#loading').toggle(bool);
},
eventRender: function(event, el) {
// render the timezone offset below the event title
if (event.start.hasZone()) {
el.find('.fc-title').after(
$('<div class="tzo"/>').text(event.start.format('Z'))
);
}
},
eventClick: function(calEvent, jsEvent, view) {}
});
I feel like being able to click and drag how much time you desire for an event is not an issue. That is unless I am missing something in your question. Is it assumed the user only needs to block off 5 minute segments?
If you really want to prevent it from dragging, you can disable it through jQueryUI
myObject.draggable( 'disable' )
Hope this helps!

Fullcalendar: How to remove event

Thanks to another post here on StackOverflow, I added some code to my select: method that prevents users from adding an event on a date prior to NOW.
The downside is that when they click on the empty time slot, and the system then complains (an alert message), the attempted event remains. How do I get rid of it? Thanks!
Update: Here's my code:
select: function(start, end, jsEvent) {
var check = start._d.toJSON().slice(0,10),
today = new Date().toJSON().slice(0,10),
m = moment(),
url = "[redacted]",
result = {};
title = "Class",
eventData = {
title: title,
start: start,
end: start.clone().add(2, 'hour'),
durationEditable: false,
instructorid: 123,
locationid: 234
};
if(check < today) {
alert("Cannot create an event before today.");
$("#calendar").fullCalendar('removeEvents', function(eventObject) {
return true;
});
} else {
$.ajax({ type: "post", url: url, data: JSON.stringify(eventData), dataType: 'JSON', contentType: "application/json", success: function(result) {
if ( result.SUCCESS == true ) {
$('#calendar').fullCalendar('renderEvent', eventData, true);
$('#calendar').fullCalendar('unselect');
} else {
alert(result.MESSAGE);
}
}});
}
}
If you're using FullCalendar V2, you need to use the removeEvents method.
You can use it to delete events with a certain ID by calling it in this way:
$("#calendar").fullCalendar('removeEvents', 123); //replace 123 with reference to a real ID
If you want to use your own function that decides whether or not an event get's removed, you can call it this way:
$("#calendar").fullCalendar('removeEvents', function(eventObject) {
//return true if the event 'eventObject' needs to be removed, return false if it doesn't
});
FullCalendar has a removeEvent method that uses an id when you create the event.
Example Full Calendar v1:
var calendar = $('#calendar').fullCalendar({ ... stuff ... });
calendar.fullCalendar( 'addEventSource', {id:123, stuff:'stuff'});
// ... other calendar things here...
calendar.fullCalendar( 'removeEvent', 123);
Reference API v1
Example FullCalendar v2:
var calendar = $('#calendar').fullCalendar({ ... stuff ... });
calendar.fullCalendar( 'addEventSource', {id:123, stuff:'stuff'});
// ... other calendar things here...
calendar.fullCalendar( 'removeEvents', [123]);
Reference API v2
Version 4.3
calendar = new Calendar(calendarEl, {
plugins : [ 'interaction', 'dayGrid', 'list' ],
header : {
left : 'prev,next today',
center : 'title',
right : 'dayGridMonth,timeGridWeek,timeGridDay,list'
},
editable : true,
droppable : true,
eventReceive : function(info) {
alert(info.event.title);
},
eventDrop : function(info) {
alert(info.event.title + " was dropped on "
+ info.event.start.toISOString());
if (!confirm("Are you sure about this change?")) {
info.revert();
}
},
eventClick : function(info) {
//delete event from calender
info.event.remove();
}
});
calendar.render();
});
Full calendar version 4
How to remove event from calendar:
<div id="calendar"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new Calendar(calendarEl, {
events: [
{
id: '505',
title: 'My Event',
start: '2010-01-01',
url: 'http://google.com/'
}
// other events here
],
eventClick: function(info) {
info.jsEvent.preventDefault(); // don't let the browser navigate
if (info.event.id) {
var event = calendar.getEventById(info.event.id);
event.remove();
}
}
});
});
</script>
This worked for me. I hope, this will also help you. Thanks for asking this question.

Categories

Resources