How to cancel old selection in fullCalendar? - fullcalendar

I use jQuery fullCalendar (http://arshaw.com/fullcalendar/docs/selection/unselectAuto/)
I use Selectable version of this calendar (http://arshaw.com/js/fullcalendar/demos/selectable.html)
It's working fine however I want to cancel/delete my old selections if I continue selecting new dates.
Lets say I chose 1 Jan and gave a title to it.
When I try to select 2 Jan, I want to see only 2 Jan selection.
I thought unselectAuto is for this but I couldnt manage to make it work :(
Any ideas?
I used unselectAuto right under
selectable: true,
unselectAuto: true,

First it's still necessary to use the $('#yourCalendar').fullCalendar('unselect'); function.
The second thing that I needed to do, was to specify how the unselect callback was going to behave (when setting up the fullcalendar options). For me I had to unbind the submit button from my form
unselect: function(){
$('#submitButton').unbind();
},
It worked great!
I was able to reach this conclusion after reading this post "multiple events created"

u can try this way, this works for me :)
var liveDate = new Date(); // current Date
var calendar = $('#calendar').fullCalendar({
select: function (startDate, endDate) {
if (liveDate > startDate) {
alert('Selected date has been passed');
return false;
} else {
//do your wish
}
calendar.fullCalendar('unselect');
}
});

Had the same problem but my user was interfacing directly with the calendar and multiple events were being generated. ie. not through a form with a button and therefore nothing to "unbind" as many of the previous solutions.
To only allow one selection and to clear previous submissions I changed the select function as follows:
select: function(start, end) {
var title = "Desired Booking";
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); },
select: function(start, end) {
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('rerenderEvents')
var title = "Desired Booking";
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); },
This did the trick for me.

I had problems with unselectAuto also. Sometimes it would unselect when I didn't want it to, and sometimes it would NOT unselect when I DID want it to. My solution was to manually trigger the unselect method.
Here's how to unselect all currently selected:
$('#yourCalendar').fullCalendar('unselect');
You can put this line of code inside custom jQuery events that you bind outside of the plugin. You can also include it in fullCalendar callbacks, etc...
Hope this helps.
Scott

Here is an exemple of Version 5 doing the unselect
You could do it by :
const calendarApi = selectInfo.view.calendar;
calendarApi.unselect(); // clear date selection

Use this code
$('#trainings_modal').on('hidden', function () {
$('#trainings_modal *').unbind(); // Unbind all events
});
Unbind on hide form with any method (i.e esc press, or out key)

Related

Protractor e2e test fullcalendar drag & drop

I need to simulate a drag & drop on fullcalendar in the week view with protractor. I found something with coordinates but I'd like a "no browser window dependent solution"... ther's also no way out on finding the exact starting cell in the week view by class or id ...or at least, I couldn't figure how to select a single cell of a row of a day because, using the Chrome's item selector, it seems every row has the same class fc-widget-content and cells are not "selectable" elements.
Are there any other chances?
maybe this is a little bit helpful (also very later ;). I also want to test my app with FullCalendar, but I'm using Cypress (similar to Protractor).
We plan items from an external list and assign it to a resource on a certain day/time in the FullCalendar (we use the scheduler plugin).
I found out that the drag and drop event is somehow intercepted by code, enriching it with for example properties of the event (like date, title and others). How I enriched this data is in the Cypress trigger('drop', data) command. Data is the evenData that is set by the Draggable class:
// Executed on the external list items, where every item we want to plan has class `.fc-event`.
this.draggableContainer = new Draggable(this.containerEl.nativeElement, {
itemSelector: '.fc-event',
eventData(eventEl) {
const id = eventEl.dataset.id;
return {
duration,
id: currentWorkItem.id,
title: currentWorkItem.description,
extendedProps: {
duration,
customRender: true,
data: currentWorkItem,
},
};
}
Then, in your test file (Cypress)
const eventData = {
date: new Date(),
dateStr: new Date().toISOString(),
draggedEl: {
dataset: {
notificationId: '123',
priority: '0',
title: 'Test',
},
},
jsEvent: null,
resource: {
id: '123',
},
event: null,
oldEvent: null,
};
cy.get('.fc-event') // selector for the external event I want to drag in the calendar
.trigger('dragstart')
.get('.fc-time-grid table tr[data-time="07:00:00"] td.fc-widget-content:nth-child(2)') // selector for where I want to drop the event.
.trigger('drop', eventData) // this will fire the eventDrop event
So, .trigger('drop', eventData) will fill the eventDrop info. It is not exactly the same as doing it manually, but works for me.
Caveats:
I haven't found a way to plan it on another resource (we use the resource scheduling plugin of FullCalendar.io). It does not matter that much, because you can specify it in the evenData (resource: { id: 'my-resource-id' } }.
No visual feedback because the drag mirror is not shown. Not a big problem during e2e testing, but it is a bit of a blackbox now. Maybe this is fixable

FullCalendar skips back to current date rather than staying on current month

I have FullCalendar installed and working great, pulling in courses from my database.
You can view different courses based on clicking a button that submits the page again but passes different criteria.
The Issue is that on reloading of the page and the new content it skips back to the current date which is rather annoying when when you are looking at courses 3 months into the future!!
Does anybody know how to make the calendar go back to the page you where on after you have refreshed the page???
I have a feeling it might be something to do with getdate as I got the following code to work but can't seem to pass the result back through the URL and into the calendar setup.
$('#my-button').click(function() {
var d = $('#calendar').fullCalendar('getDate');
alert("The current date of the calendar is " + d);
});
If you use jquery.cookie you can store the currently viewed date in a cookie for the page being viewed and use that value to set the defaultDate when the page reloads. Pass these in as options when you initialise your calendar:
defaultView: Cookies.get('fullCalendarCurrentView') || 'month',
defaultDate: Cookies.get('fullCalendarCurrentDate') || null,
viewRender: function(view) {
Cookies.set('fullCalendarCurrentView', view.name, {path: ''});
Cookies.set('fullCalendarCurrentDate', view.intervalStart.format(), {path: ''});
}
This code also saves the current view (e.g. month, day etc...)
I used a combination of the two above. I set the localStorage value for the start date when creating, moving, or resizing an event as well as viewRender and then assigned that value to the defaultDate.
defaultDate: localStorage.getItem('Default_FullCalendar_Date'),
viewRender: function(view) {
localStorage.setItem('Default_FullCalendar_View', view.name);
...
},
select: function(start, due){
localStorage.setItem('Default_FullCalendar_View', start);
...
},
eventDrop: function(event, delta, revertFunc, jsEvent, ui, view){
localStorage.setItem('Default_FullCalendar_View', event._start._d);
...
},
eventResize: function(event, delta, revertFunc, jsEvent, ui, view){
localStorage.setItem('Default_FullCalendar_View', event._start._d);
...
}
Works like a charm.
You can use gotoDate method:
var d = $('#calendar').fullCalendar('getDate');
$('#calencar').fullCalendar( 'gotoDate', d.getFullYear(), d.getMonth(), d.getDate() )
Here is an updated answer for version 4 and 5 of fullcalendar.
since viewRender is no longer an option in these versions. I came up with a different approach using the loading option.
The loading option will give you a boolean argument stating whether the calendar is done loading or not. Inside that function I check if the calendar is done loading and if so, I set the calendar date to localStorage. Next I created an if else statement before the fullcalendar object to check if the localstorage item exists, and if so I set the defaultDate option in the calendar object to to localStorage date; if not, I just set it to today's date.
Example:
let viewDate;
const savedDate = localStorage.getItem("calDate");
if (savedDate !== null) {
viewDate = new Date(savedDate);
} else {
viewDate = today();
}
const calendarElement = document.getElementById('your_calendar');
const calendar = new FullCalendar.Calendar(calendarElement, {
defaultDate: viewDate,
loading: function(stillLoading) {
if (stillLoading === false) {
// When Calendar is done loading....
localStorage.setItem("calDate", calendar.getDate());
}
},
});

fullCalendar adding a class to events

I am trying to select events on fullcalendar, based on user selection.
Example: if user selects class A, then all classes with the same ID should turn green (using applied className).
I am having trouble applying classes to the other events that I can successfully select by ID. I guess my issue is combining the event objects with jQuery objects.
sample code:
eventClick: function(event) {
$(this).addClass("reg_selected"); //this works fine on selected event
var selectedID = event.id
alert(selectedID); //get event.ID, and use it to find similar ones.
var similarEvents = $("#calendar").fullCalendar('clientEvents',selectedID).addClass("reg_selected");
the error I get is:
addClass is not a function
I also tried this method of looping, and got the same error:
for (var i = 0; similarEvents.length > i ; i++){
alert(similarEvents[i].title);
similarEvents[i].className("reg_selected");
}
the alert() worked, but the className() generated the same error as above
This answer for a very similar situation, but when event classes are selected with round-trip to the event source for possible persistence in the db or checks.
Class name can be specified in the event object in the source as follows (start and end given for the context only):
[{
...
"className": "selected-event",
"start": '2017-05-01T08:30:00.0',
"ends": '2017-05-01T09:00:00.0',
...
}, ...]
The idea is that user clicks the event; ajax call to select events goes to backend; onsuccess, frontend javascript does$calendar.fullCalendar('rerenderEvents'); and receives the event source with events' classes. The immediate child of .fc-event-container gets the specified class, in the example above - selected-event.
As a result, the selection can be persisted on the backend.
clientEvents returns an array of matching objects. You need to iterate through the array (in your case similarEvents) and call addClass for each item
Update:
There is also issues using an id to update multiple events, using a filter function instead is a better way to go.
eventClick: function(event) {
var similarEvents = $("#calendar").fullCalendar('clientEvents', function(e) { return e.test === event.test });
for (var i = 0; similarEvents.length > i ; i++){
similarEvents[i].className = 'reg_selected';
$('#calendar').fullCalendar('updateEvent', similarEvents[i]);
}
},
See jsfiddle
For fullcalendar add event class, id and title see this.
if($('#eventTitle').val() == "Avilable") {
eventClass = "avilable";
}else {
eventClass = "unavilable";
}
$myCalendar.fullCalendar('renderEvent', {
id:response,
title: title.val(),
start: start.val(),
end: end.val(),
allDay: true,
className: eventClass,
color: color
}, true
);
I was able to get it working with the following code:
eventRender: function (eventObj, $el) {
$el.addClass(eventObj.ClassName);
},
eventObj.ClassName = "calendar-priority-warning"

How to get form values for a special component (bootstrap-daterangepicker)?

I am using bootstrap-daterangepicker in a form. The way I am currently grabbing the value of this selection works but the way I am getting the values doesn't seem like a good way.
It seems bad to use the Session to hold the field selections and then unset them when i am done. I just want to be sure that I am not missing something.
I could get the value from the input field but I would have to parse the string to pull the dates out. Doping this could be a maintenance headache because I would need to change the parsing if I change the daterangepicker date formats.
The form field:
<input type="text" name="carpool_eventDates" id="carpool_eventDates" />
JS to activate the component:
Template.add_event.rendered = function () {
// initialize add event modal;
$('#addEvent')
.modal();
// initialize the date range picker
$('input[name="carpool_eventDates"]').daterangepicker(
// default date range options
{ranges: {'Last 5 Days': [Date.today().add({ days: -4 }), 'today'],
'Next 5 Days': ['today', Date.today().add({ days: 4 })]}
},
// grab the selection
function(start, end) {
Session.set("showAddEventDialogue_dateRangeStart",start);
Session.set("showAddEventDialogue_dateRangeEnd",end);
});
};
JS save button click handler:
Template.add_event.events({
'click button.save-addEventDialogue': function(e, tmpl) {
// Get the date range selection from the session
var start = Session.get("showAddEventDialogue_dateRangeStart");
var end = Session.get("showAddEventDialogue_dateRangeEnd");
// Do something with the dates
// Clear the dates from the session now that we are done with them
Session.set("showAddEventDialogue_dateRangeStart","");
Session.set("showAddEventDialogue_dateRangeEnd","");
// Close the dialogue
Session.set("showAddEventDialogue", false);
}
});
Is this a good way to do this? Or is there a better way?
Thanks.
You could use jQuery's .data() to store the daterangepicker data on the original <input> element, rather than in Session. So you could rewrite your "grab the selection" code thus:
// grab the selection
function(start, end) {
$('input[name="carpool_eventDates"]')
.data("showAddEventDialogue_dateRangeStart", start)
.data("showAddEventDialogue_dateRangeEnd", end);
});
Then you retrieve the data from the element, rather than from Session:
// Get the date range selection from the element
var start = $('input[name="carpool_eventDates"]').data("showAddEventDialogue_dateRangeStart");
var end = $('input[name="carpool_eventDates"]').data("showAddEventDialogue_dateRangeEnd");
And assuming the <input> is discarded when the modal is closed and template destroyed, you have no Session or other variables to clean up.

Make Event Background Color Unique on a Per-event Basis

I am sure there is a simple solution, but after reading existing posts and the documentation, I haven't been able to locate it just yet. This is my first post here, so any help is much appreciated.
I am integrating the FullCalendar with ExpressionEngine and the Calendar module for EE, and I have events rendering in FancyBox.
My only remaining issue is that the background of each event is the same color. What I am wanting to accomplish is on any given day, make multiple events have a different background color to identify the event as unique. In the documentation, it explains how to change the background color, but it's an "all-or-nothing" solution.
I also attempted to tweak the styles, but this made every day cell have the background color, rather than the actual individual events.
The code that builds the calendar and populates events from EE is listed as follows:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next',
center: 'title',
right: ''
},
editable: false,
events: [ {}
{exp:calendar:events event_id="{segment_3}" sort="asc" dynamic="off"}
{occurrences}
,{title: '{event_title}',
url: '{url_title_path="path_to/event/"}',
start: new Date({occurrence_start_date format="%Y,%n-1,%j"}),
end: new Date({occurrence_end_date format="%Y,%n-1,%j"}),
allDay: true,}
{/occurrences}
{/exp:calendar:events}
],
eventClick: function(event) {
if (event.url) {
$("a").fancybox(event.url);
return false;
}
}
}); });
This would be simple to do if the events were manually being populated, but the data is coming from ExpressionEngine, rather than being hard-coded.
Any thoughts on how to make each event on a per-day basis render with a different background color than any of the other events listed for that same day?
Thanks for reading!!!
The current version of fullCalendar has a property on an event object '.backgroundColor' which can be set to change the background colour of that event. Of course you'd have to write some code to set up the background colours to all be unique within a day.
You may consider using the css3 nth child selectors here. This will allow CSS to automagically change the colors for you. See: http://css-tricks.com/how-nth-child-works/
You would of course need to target the appropriate elements, but without seeing the full DOM it will be very difficult for us to help with that here.
You can use eventAfterAllRenderwhich is triggered after all events have finished rendering in the fullCalendar from both source.
eventAfterAllRender: function( view ) {
var allevents = $('#calendar').fullCalendar('clientEvents');
}
Now, with the allevents object, you can do whatever toy wish.
Here is the one I took for me:
eventAfterAllRender: function(view) {
var allevents = $('#calendar').fullCalendar('clientEvents');
var countevents = 0;
if( allevents.length ) {
countevents = countevents + allevents.length;
}
if(!countevents) {
// alert('event count is'+countevents);
console.log('event count is',countevents);
}
}
One of my friend was able to get the id of duplicate events and now I can delete the duplicate event within a loop as:
$('#calendar').fullCalendar('removeEvents', allevents[i].id);
Now it is up to you. Very sorry because I am running a busy schedule nowadays. I'm glad if someone would generate a proper solution for Mr. Lane from this(even by editing this answer).
Thank you.

Resources