How to remove allDay from view in fullcalender JS? - javascript

I am trying to build an application that creates events within fullcalendar. I don't allow user to create an "allDay" event at all at the client side but they still can see it within the view. Is there any method to remove allDays from views completely?
function initCalendar {
if (!jQuery().fullCalendar) {
return;
}
var date = new Date(),
started,
ended
var header = {};
var calendar = $('#calendar').fullCalendar({
header: header,
selectable: true,
selectHelper: true,
select: function (start, end, allDay) {
$('#fc_create').click();
var dateStart = start;
var dateEnd = end;
$(".antosubmit").on("click", function() {
var title = $("#reservation-title").val();
if (title) {
var event = {
editable: true,
title: title,
start: dateStart,
end: dateEnd,
allDay: false
}
calendar.fullCalendar('renderEvent', event, true);
calendar.fullCalendar('unselect');
#('.antoclose').click();
return false;
}
else {
////alert here
}
})
}
})
}

From the docs:
allDaySlot: false
https://fullcalendar.io/docs/agenda/allDaySlot/
** Update for v5:
https://fullcalendar.io/docs/allDaySlot

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

FullCalendar trying to fetch events from URL instead of array

Using FullCalendar v3.9.0 with jQuery v3.3.1. I have a SailsJS application that's getting the calendar data from MySQL.
this.me.calendar from MySQL currently looks like this.
[{"start":"2018-07-04T13:30:00","end":"2018-07-04T18:00:00","works":["2"]}]
And my FullCalendar code looks like this.
let that = this;
that.me.calendar = this.me.calendar;
$('#calendar').fullCalendar({
header: {
left: 'today prev,next',
center: 'title',
right: 'agendaWeek,agendaDay'
},
views: {
week: {
titleFormat: 'DD.MM.YYYY'
}
},
defaultView: 'agendaWeek',
locale: 'fi',
weekends: false,
scrollTime: '07:00',
businessHours: {
start: '7:00',
end: '21:00',
},
events: function(start, end, timezone, callback) {
let events = that.me.calendar ? that.me.calendar : [];
console.log(events);
callback(events);
},
editable: true,
selectable: true,
selectHelper: true,
select: (start, end) => {
let duration = (end - start) / 1000;
if (duration == 1800) {
// Set default duration to 1 hour
end = start.add(30, 'mins');
return $('#calendar').fullCalendar('select', start, end);
}
let eventData = {
start: start,
end: end,
works: []
}
$('#calendar').fullCalendar('renderEvent', eventData);
$('#calendar').fullCalendar('unselect');
},
eventClick: (event, element) => {
$('#event-works').text(event.works.join(','));
$('#start-date').text(moment(event.start).format('d.MM.YYYY HH:mm'));
$('#end-date').text(moment(event.end).format('d.MM.YYYY HH:mm'));
$('#workModal').modal('show');
$('#add-work-to-event').click(() => {
let work = $('#work').val();
if(_.includes(event.works, work)) return;
event.works.push(work);
$('#event-works').text(event.works.join(','));
});
}
});
While the code above doesn't send the GET, it doesn't display the events in the calendar. However, if I change the events to events: this.me.calendar, the SailsJS console displays GET /account/%22[%7B/%22start/%22:/%222018-07-04T13:30:00/%22,/%22end/%22:/%222018-07-04T18:00:00/%22,/%22works/%22:[/%222/%22]%7D]%22 (1ms 404).
I also tried changing it to events: JSON.stringify(this.me.calendar), which still gave the GET request in console.
If I enter the array in the events on it's own, it is working. Also the console.log inside the events function is returning the same array.
Is there a way for me to simply enter my array for FullCalendar, or do I have to make it get the JSON from an URL?
I managed to solve the issue by changing the let events inside of my events function to let events = that.me.calendar ? JSON.parse(that.me.calendar) : []; and now the events are being displayed.

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");
}
}

How to register an event using addEventSource in fullCalendar?

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');
},

"this.model" not working on clicked View. Backbone JS

A quick explanation:
I am working on a backbone app that integrated with Fullcalendar JS. When creating or editing an event, you can click on the calendar and a modal will popup asking for the info. The problem is when the modal pops up I need to use "this.model" to .get() info about the current event or .set() info about a new event. I keep getting the error:
Uncaught TypeError: Cannot call method 'get' of undefined
Uncaught TypeError: Cannot call method 'set' of undefined
My question:
What is the proper method to set the current model of a clicked view?
Here is some relevant code:
Model & collection:
var Event = Backbone.Model.extend({
methodToURL: {
'create': addDayURL,
'update': addDayURL,
//'delete': '/user/remove'
},
sync: function(method, model, options) {
options = options || {};
options.url = model.methodToURL[method.toLowerCase()];
Backbone.sync(method, model, options);
}
});
var Events = Backbone.Collection.extend({
model: Event,
url: allDaysURL
});
Main View
var EventsView = Backbone.View.extend({
events: {
'click #add_track' : "addTrack",
'click th.fc-widget-header:not(.fc-first)' : 'updateTrack',
'click .fc-button-next' : 'switchTracks',
'click .fc-button-prev' : 'switchTracks'
},
initialize: function(){
_.bindAll(this);
this.collection.on('reset', this.addAll);
this.collection.bind('add', this.addOne);
this.collection.bind('change', this.change);
this.collection.bind('destroy', this.destroy);
console.log(this.collection.toJSON());
console.log(JSON.stringify(this.options.collection2.toJSON()))
this.trackCollection = JSON.stringify(this.options.collection2.toJSON());
this.trackObject = jQuery.parseJSON(this.trackCollection);
this.eventView = new EventView();
this.trackView = new TrackView();
},
render: function() {
this.$el.fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaDay',
},
defaultView: 'resourceDay',
resources: this.trackObject,
droppable: true,
selectable: true,
selectHelper: true,
editable: true,
ignoreTimezone: false,
select: this.select,
eventClick: this.eventClick,
eventDrop: this.eventDropOrResize,
eventResize: this.eventDropOrResize,
drop: function(date, allDay, ev, ui, res) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
// dropped event of resource a to a cell belonging to resource b?
copiedEventObject.resourceId = res.id;
//get title of event
var eventTitle = copiedEventObject.title;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
var event = new Event();
event.set({"title": eventTitle, "start_at": copiedEventObject.start, "color": null, "allday":copiedEventObject.allDay, "conference_id": conferenceID, "session_type_id": 1, "resource_Id": res.id});
events.create(event);
}
});
//Goto first event day on initialize
var start_at = Date.parse(startDate);
var year = $.fullCalendar.formatDate(start_at, 'yyyy');
var month = $.fullCalendar.formatDate(start_at, 'M');
var day = $.fullCalendar.formatDate(start_at, 'dd');
this.$el.fullCalendar( 'gotoDate', year , month, day)
this.$el.prepend('<button id="add_track" class="btn large-btn green-btn pull-right">Add Track</button>');
},
addAll: function() {
this.$el.fullCalendar('addEventSource', this.collection.toJSON());
},
addOne: function(event) {
this.$el.fullCalendar('renderEvent', event.toJSON());
},
addTrack: function() {
//get current day & format date
date = this.$el.fullCalendar( 'getDate' );
var formatDate = $.fullCalendar.formatDate(date, 'yyyy-MM-dd');
//create new track
var newTrack = new Track;
newTrack.set({'name': 'Track 1', 'day_date': formatDate, 'conference_id': conferenceID, "session_type_id": 1});
//save track to DB
this.options.collection2.create(newTrack);
},
updateTrack: function(track) {
//var fcRes = this.$el.fullCalendar('clientEvents', event.get('id'))[0];
//this.trackView.model = track.get('id');
console.log(this.trackView.model)
this.trackView.render();
},
switchTracks: function(){
//alert(this.$el.fullCalendar( 'getDate' ))
},
select: function(startDate, endDate, res) {
this.eventView.collection = this.collection;
this.eventView.model = new Event({start_at: startDate, end_at: endDate});
this.eventView.render();
},
eventClick: function(fcEvent) {
this.eventView.model = this.collection.get(fcEvent.id);
this.eventView.render();
},
change: function(event) {
// Look up the underlying event in the calendar and update its details from the model
var fcEvent = this.$el.fullCalendar('clientEvents', event.get('id'))[0];
console.log(fcEvent);
fcEvent.title = event.get('title');
fcEvent.color = event.get('color');
this.$el.fullCalendar('updateEvent', fcEvent);
},
eventDropOrResize: function(fcEvent) {
alert(fcEvent.id)
// Lookup the model that has the ID of the event and update its attributes
this.collection.get(fcEvent.id).save({start: fcEvent.start, end: fcEvent.end});
},
destroy: function(event) {
this.$el.fullCalendar('removeEvents', event.id);
}
});
Event Popup Modal View
var EventView = Backbone.View.extend({
el: $('#eventDialog'),
initialize: function() {
_.bindAll(this);
},
render: function() {
var buttons = {'Ok': this.save};
if (!this.model.isNew()) {
_.extend(buttons, {'Delete': this.destroy});
}
_.extend(buttons, {'Cancel': this.close});
this.$el.dialog({
modal: true,
title: (this.model.isNew() ? 'New' : 'Edit') + ' Event',
buttons: buttons,
open: this.open
});
return this;
},
open: function() {
this.$('#title').val(this.model.get('title'));
this.$('#color').val(this.model.get('color'));
},
save: function(startDate, endDate, res) {
//copiedEventObject.resourceId = res.id;
this.model.set({'title': this.$('#title').val(), 'color': this.$('#color').val(), 'conference_id': conferenceID, "session_type_id": 1, 'track_id': 1, /*'resourceId': res.id*/});
if (this.model.isNew()) {
this.collection.create(this.model, {success: this.close, wait: true});
} else {
this.model.save({}, {success: this.close});
}
},
close: function() {
this.$el.dialog('close');
},
destroy: function() {
this.model.destroy({success: this.close});
}
});
It looks like your calendar view does not have a model associated with it. You will need to pass the model into the calendar view when instantiating it. When you call this.eventView = new EventView(); you are not providing it with a reference to your underlying model in your main view.

Categories

Resources