how to call fullcalendar events() with a paremeter? - fullcalendar

Is there a way to filter events based on a drop down?
I tried :
events: '/Controller/action?id='+id,
$("#drop").change(function () {
id = $('#drop').val();
$('#calendar').fullCalendar('refetchEvents');
But the controller does not see the new id.
Any suggestions on passing a paremter to the events() method?

You gave the result of '/Controller/action?id='+id to the calendar as the events feed when the calendar was initialised. e.g. you passed in /Controller/action?id=3, for example. That code has run and does not run again. fullCalendar stores that static string as the URL of the events feed. It doesn't pay any attention to the value of "id" later.
The simplest way to solve this is probably using a custom event feed, as per https://fullcalendar.io/docs/event_data/events_function/ :
//declare the calendar with a custom "events" functions
$("#calendar").calendar({
//..all your calendar options, and then the events:
events: function( start, end, timezone, callback ) {
$.ajax({
//whatever ajax parameters you need, but make sure:
url: /Controller/action,
data: { "id": $('#drop').val(), "start": start.format("YYYY-MM-DD"), "end": end.format("YYYY-MM-DD") }
});
}
});
$("#drop").change(function () {
$('#calendar').fullCalendar('refetchEvents');
});
That way, when "refetchEvents" is called, it runs the function that you passed as the "events" parameter, which can look up the value of the dropdown dynamically at that moment in time.
Note I've also added "start" and "end" parameters to your data, because your event source is supposed to filter the events returned by the dates actually being displayed on the calendar, otherwise you end up returning all events every time the view or date changes.

Related

Google Insert Events Duplicating In Google Calendar By Clicking Insert Button again and again

I have used a button for inserting events but when i click button again it inserts again and created a duplicate copies of events. Is there any way to only insert latest events.
{
var request;
for (var j = 0; j < this.state.syncEvent.length; j++) {
console.log("J loop", this.state.syncEvent[j]);
request = function (resource) {
return gapi.client.calendar.events.insert({
'calendarId': 'primary',
'eventId': resource
});
}(this.state.syncEvent[j]);
request.execute(function (resp: any) {
console.log(resp);
});
}
}
If you are inserting an event with a predefined event id - check first if an event with this id already exists
First of all, there are some problems with your code.
Have a look at the Javasript sample in the documentation:
The correct syntax would be:
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
whereby event is the event resource of type
var event = {
...
'start': {
'dateTime': '2015-05-28T09:00:00-07:00',
'timeZone': 'America/Los_Angeles'
},
'end': {
'dateTime': '2015-05-28T17:00:00-07:00',
'timeZone': 'America/Los_Angeles'
},
'id': SPECIFY_HERE_THE_EVENT_ID,
...
};
The event resource must contain the Required Properties end and start, in addition you specify additional properties mentioned in the documentaiton of the method like e.g. summary or id.
Now, since from your code snippet one can deduct that you pass the event id to your function - before inserting the event, you can check with the method Events: get either an event with the given id already exists.
Alternatively, you can also use the method Events: list to retrieve the already existing events in your calendar. Thereby you can use the query parameter q to filter by e.g. summary or you can query by specifying the paramters timeMax and timeMin - depending on your use case.
All you need to do is to implement a conditional statement to create a new event only if Events: get or Events: list did not return an already existing event with the specified parameters.

Fullcalendar --> Send selected year

i use fullcalendar and want to send the year of the selected view (not the current view) to the page "ajax_load_projektkalender.php".
The following try results in an error:
events: {
url: 'ajax_load_projektkalender.php',
type: 'POST',
data: function() { // a function that returns an object
return {
projekte_key: $('#projekte_key').val(),
aufgaben_key: $('#aufgaben_key').val(),
sel_year: $('#calendar').fullCalendar('getView').start.format('Y'),
urlaub_key: $('#urlaub_key').val(),
termine_key: $('#termine_key').val()+'',
gruppiert_key: $('#gruppiert_key').val(),
bdauer_key: $('#bdauer_key').val()
};
},
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
Error: TypeError: $(...).fullCalendar(...).start is null
[Weitere Informationen]
I' m helpless... can anybody give me advice ?
Daniel
You have a bootstrap problem: you define the events of your calendar by referencing the current view, but that will be empty until you have defined the events of your calendar... To break the loop, assuming that initially you want to display the current year, you could write something like:
data: function() {
var current = $('#calendar').fullCalendar('getView').intervalStart
var y = (current?current:moment()).format('Y')
return {
...
sel_year: y,
...
}
I am not sure what you are trying to do, but actually I suspect you don't need that at all, as fullcalendar automatically adds to the ajax request to your php server a parameter "start" holding the start date of the period to display in ISO format (and similarly an "end" parameter). You can even give an alternative names to your parameters using e.g.
startParam: 'Anfang'
in your calendar objet.
Try intervalStart instead of start. That should fix the error, but I am not sure it solves your problem.

ASP.NET MVC: Save multiple values on autocomplete

I have a mysql database with the tables "deliverables", "tags" and "deliverables_has_tags". I want to link tags to a deliverable.
This is what I do in my javascript file:
<script type="text/javascript" language="javascript">
$(function () {
var object = {};
$.ajax({
type: "GET",
url: "/Deliverable/Tags",
dataType: "json",
success: function (data) {
object.tags = data;
}
});
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
object.tags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
I can add multiple tags in my textbox.
But now I want to save this in my repository.
In my Action method in controller:
repository.AddDeliverable(model.Title, model.Description, model.UsernameID, data, datatwo, model.VideoUrl, model.AfstudeerrichtingID, model.ProjectID);
Tags action:
public JsonResult Tags()
{
var data = (repository.GetTags()).ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
In my repository:
public IQueryable<string> GetTags()
{
return from tag in entities.tags
orderby tag.tag_name
select tag.tag_name;
}
I have no clue how to save this in my database.
Can anybody help me?
If I correctly understood your question, you have implemented your tag handling as follows:
There is MVC action method that returns the view with input placeholder containing no data
The placeholder itself is probably input type=text with id=tags
On 'dom ready' you fire ajax request to retrieve your tags from database, json-serialized as array; when it arrives you store it to tags variable (no error handling(!))
At the same time you decorate your input with jqueryui autocomplete that reacts on user input and returns items from the tags variable
Since input already contains tags (comma separated), your filter is first letters of the last tag
So, you have a situation when user has input a few comma separated tags (probably some of them can be new) and now wants to save it to the database. For each input, if that is a known tag you have to store it to "deliverables_has_tags". If there is a new tag, you have to store it both to "tags" and "deliverables_has_tags".
Most common scenario would be having a 'Save' button to start saving process.
Let's analyze what you have to do in the process.
1) Button click
On button click you use js to convert your comma separated tags string
using logic like split(term) to the array, and serialize it. You can
do serialization using serializeArray and manually create JSON
object, or serialize the whole form using
$('#yourForm').serialize(). I would choose the first option
because that way I get more control over JSON format and avoid
problems with MVC default model binder.
2) Ajax call
When the JSON object is ready to be sent, you fire an ajax POST
request to your MVC POST action method. When you save state always
avoid GET because new versions of browsers can scan thru your page and
actively preload urls using GET requests. You don't want this here. Of
course, use your data as a data-parameter in the ajax call.
3) Action method
When the request arrives, you have to process it in your controller
using a new action method. Typically in this case you will have
something like public JsonResult SaveTags(SaveTagsModel saveTags) {
... } which saves tags using your repository and returns result that
says something like 'OK' or 'ERROR' (sth like
response.isSaved=true/false). Tricky part can be designing view model
according to your JSON object - this could help. And regarding
collections this could be valuable info.
When saving, use transaction to ensure everything is saved at once.
First check if each tag exists in the database and insert those who
don't exist. After that, check for each tag if there is appropriate
n-n relation in deliverables_has_tags and insert it if there isn't.
I believe that you should use same repository encapsulation for both
operations.
In the post action, include FormCollection collection as argument and gather your tags from that. There is no automatic way. You could implement some custom model binding, but that is probably not worth the effort.

FullCalendar passing starting date

Can someone help me understand how I can pass the start date into the calendar. I have created a Delivery Scheduler calendar and I display the delivery details in a table under the calends that is feed via the database. This requires me to refresh the page when a user select a calendar day to load the table information. I can figure out how to start the calendar on a starting date that is passed into the page.
Seems like this would be easy but I am doing something wrong.
$('#calendar').fullCalendar(Options);
$('#calendar').fullCalendar('gotoDate', '2012-10-21');
Sample based on documentation http://arshaw.com/fullcalendar/docs/current_date/gotoDate/
Remember that month is 0-based, so 10 means November.
$(document).ready(function () {
var calendar = $('#calendar').fullCalendar({
events:[
{ title:'All Day Event', start:new Date(2012, 10, 20)},
{ title:'Long Event', start:new Date(2012, 10, 21), end:new Date(2012, 10, 22)}
]
});
$('#calendar').fullCalendar('gotoDate', 2012, 10, 21);
});
Thank you Biesior for your helpful answer. I was able to use your suggested code to get the behavior I was looking for.
While using the approach above, I notice that Firebug's console shows two AJAX data requests being executed simultaneously, one for the view associated with the current date, and one for the view associated with the specified gotoDate.
There doesn't appear to be any additional delay from the user's perspective, and the calendar displays the requested view from the start. However, 'loading' callbacks will be called multiple times which might cause strange behavior in certain circumstances. There may also be other undesired results associated with the superfluous AJAX request for the current date.
I was able to avoid the unnecessary AJAX request by initializing the calendar without an event source, then moving to the desired date as shown by Biesior above, and then adding the event source. The sequence is shown below. I've removed some unrelated FullCalendar options and callbacks to keep it concise. There are some additional AJAX parameters, and some PHP, but the important thing to notice is when the event source is specified.
The original code results in two simultaneous AJAX requests:
$('#calendar').fullCalendar({
events: {
url:'/Services/GetEvents.php',
type: 'POST',
data: {
lat: <?=$venLatitude?>,
lon: <?=$venLongitude?>,
userID: <?=$userID?>,
distance: <?=$distance?>
}
}
})
$('#calendar').fullCalendar('gotoDate', <?=(int)substr($startDate,0,4)?>, <?=((int)substr($startDate,5,2))-1?>);
This adjustment results in only the desired AJAX request:
$('#calendar').fullCalendar();
$('#calendar').fullCalendar('gotoDate', <?=(int)substr($startDate,0,4)?>, <?=((int)substr($startDate,5,2))-1?>);
$('#calendar').fullCalendar('addEventSource', {
url:'/Services/GetEvents.php',
type: 'POST',
data: {
lat: <?=$venLatitude?>,
lon: <?=$venLongitude?>,
userID: <?=$userID?>,
distance: <?=$distance?>
}
});

Fullcalendar async loading and display of event sources

I've set up my events sources to pull from two different endpoints. One of these endpoints is heavy and happens to take two seconds longer than the other.
My calendar appears to wait until both sources are loaded before populating the calendar.
Q: is it possible to populate the calendar with the first data source while waiting for the second to finish?
$('#calendar').fullCalendar({
eventSources: [
loadQuickEvents,
loadSlowEvents'
]
});
function loadQuickEvents (start, end, timezone, callback) {
// execute xhr, on success trigger callback
...
callback ()
}
function loadSlowEvents (start, end, timezone, callback) {
// execute xhr, on success trigger callback
...
callback ()
}

Resources