RubyOnRails3 - FullCalendar - ruby-on-rails-3

I would like to use calendar in my project, I already used table_builder gem and event_calendar gem but fullcalendar gem is more appropriate for me. The problem is I can't find any step by step tutorial to use it and somehow I'm new to RubyOnRails. Can any one help me to be able to understand how to use it please?

*I Figured Out how to use full calendar - just go to fullcalendar web site and download the required version of fullcalendar JavaScript and css files - include fullcalendar.js and fullcalendar.css in the header of layout - create a new js file called calendar and write the following code: *
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#my_calendar').fullCalendar({
editable: true,
droppable: true,
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'month',
height: 500,
slotMinutes: 15,
loading: function(bool){
if (bool)
$('#loading').show();
else
$('#loading').hide();
},
// a future calendar might have many sources.
eventSources: [{
url: '/events/index/',
color: 'yellow',
textColor: 'black',
ignoreTimezone: false
}],
dragOpacity: "0.5",
//http://arshaw.com/fullcalendar/docs/event_ui/eventDrop/
eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc){
updateEvent(event);
},
// http://arshaw.com/fullcalendar/docs/event_ui/eventResize/
eventResize: function(event, dayDelta, minuteDelta, revertFunc){
updateEvent(event);
},
// http://arshaw.com/fullcalendar/docs/mouse/eventClick/
eventClick: function(event, jsEvent, view){
window.location = ('/events/show?id=' + event.id)
},
});
});
function updateEvent(the_event) {
$.ajax({
type: 'POST',
url: '/events/update_js?id='+ the_event.id +"&startd=" + the_event.start+"&endd=" + the_event.end, //the script to call to get data
data: {end: the_event.end, start: the_event.start } , //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function() //on receive of reply
{
alert("done!")
}
});
};
There are other code in the model and view in which the calendar will appear. also I changed the code of edit event function because it didn't work with me and function in the controller of event for edit- for any help I'm here any time. hope you can use it as I did

Related

FullCalendar pass events array as simple argument

Currently iam trying to pass an array of events in my database as a simple parameter. Below i attach my backend callback, the query document and the pure javascript Full Calendar implementation. So i tried forEach but gives me error . If i pass directly the objects array anaylitically then all works fine, but my issue is that i cannot render events by providing the array variable as argument. I wont like use JSON feed feature because my api is not able to be configurated. Any suggestion welcomed, thank you in advance
calendar:35 Uncaught ReferenceError: eventsArray is not defined
at HTMLDocument.<anonymous>
Express Js Callback
exports.getcalendar=async function (req,res,next){
var bookdata={};
try{
bookdata=await booking.aggregate().match({resourceID:mongoose.Types.ObjectId(req.params.id)}).project({
'title':'$Project_title',
'start':'$date_started',
'end':'$date_finished',
'_id':0
})
}catch (error){
return next(error);
}
finally {
console.log(JSON.parse(JSON.stringify(bookdata)));
res.render('calendar',{databook:JSON.parse(JSON.stringify(bookdata))});
}
};
bookdata
[
{
title: 'prj',
start: '2021-04-08T20:25:00.000Z',
end: '2021-04-09T20:25:00.000Z'
},
{
title: 'Proej3',
start: '2021-04-12T00:58:00.000Z',
end: '2021-04-13T00:58:00.000Z'
},
{
title: 'May proj',
start: '2021-05-10T11:00:00.000Z',
end: '2021-05-11T11:00:00.000Z'
},
{
title: 'prj',
start: '2021-04-28T15:00:00.000Z',
end: '2021-04-28T18:00:00.000Z'
}
]
FullCalendar Constructor
script.
document.addEventListener('DOMContentLoaded', function (databook) {
var calendarEl = document.getElementById('calendar');
var initdate = new Date();
var calendar = new FullCalendar.Calendar(calendarEl, {
function(){
var eventsArray=[];
bookdata.forEach(function (element){
eventsArray.push({
title:element.title,
start:element.start,
end:element.end })
})
},
initialView: 'dayGridMonth',
timeZone:'Europe/Athens',
initialDate: initdate,
handleWindowResize:true,
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
eventTimeFormat:{
hour: 'numeric',
minute: '2-digit',
},
eventDisplay:'auto',
views:{
timeGrid:{
formatDateTime:'DD/MM/YYYY HH:mm'
}
},
events:eventsArray
});
calendar.addEvent()
calendar.render();
});
Don't create the eventsArray variable inside the calendar variable. You can initialize it right before the calendarEl is created for example

Using a custom Drop Down List field to set a value in a grid

I'm trying to use the Rally 2.1 SDK to set a custom data field (c_wsjf) in a grid. I have a custom drop down list that I want to check the value of (c_TimeCrticalitySizing).
I created c_TimeCrticalitySizing as a feature card field in my Rally workspace with different string values (such as "No decay"). Every drop down list value will set the custom field to a different integer. When I try to run the app in Rally I get this error:
"Uncaught TypeError: Cannot read property 'isModel' of undefined(…)"
I'm thinking the drop down list value may not be a string.
How would I check what the type of the drop down list value is?
How could I rewrite this code to correctly check the value of the drop down list so I can set my custom field to different integers?
Here's my code block for the complete app. I'm still trying to hook up a search bar so for now I directly call _onDataLoaded() from the launch() function.
// START OF APP CODE
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
featureStore: undefined,
featureGrid: undefined,
items: [ // pre-define the general layout of the app; the skeleton (ie. header, content, footer)
{
xtype: 'container', // this container lets us control the layout of the pulldowns; they'll be added below
itemId: 'widget-container',
layout: {
type: 'hbox', // 'horizontal' layout
align: 'stretch'
}
}
],
// Entry point of the app
launch: function() {
var me = this;
me._onDataLoaded();
},
_loadSearchBar: function() {
console.log('in loadsearchbar');
var me = this;
var searchComboBox = Ext.create('Rally.ui.combobox.SearchComboBox', {
itemId: 'search-combobox',
storeConfig: {
model: 'PortfolioItem/Feature'
},
listeners: {
ready: me._onDataLoaded,
select: me._onDataLoaded,
scope: me
}
});
// using 'me' here would add the combo box to the app, not the widget container
this.down('#widget-container').add(searchComboBox); // add the search field to the widget container <this>
},
// If adding more filters to the grid later, add them here
_getFilters: function(searchValue){
var searchFilter = Ext.create('Rally.data.wsapi.Filter', {
property: 'Search',
operation: '=',
value: searchValue
});
return searchFilter;
},
// Sets values once data from store is retrieved
_onDataLoaded: function() {
console.log('in ondataloaded');
var me = this;
// look up what the user input was from the search box
console.log("combobox: ", this.down('#search-combobox'));
//var typedSearch = this.down('#search-combobox').getRecord().get('_ref');
// search filter to apply
//var myFilters = this._getFilters(typedSearch);
// if the store exists, load new data
if (me.featureStore) {
//me.featureStore.setFilter(myFilters);
me.featureStore.load();
}
// if not, create it
else {
me.featureStore = Ext.create('Rally.data.wsapi.Store', {
model: 'PortfolioItem/Feature',
autoLoad: true,
listeners: {
load: me._createGrid,
scope: me
},
fetch: ['FormattedID', 'Name', 'TimeCriticality',
'RROEValue', 'UserBusinessValue', 'JobSize', 'c_TimeCriticalitySizing']
});
}
},
// create a grid with a custom store
_createGrid: function(store, data){
var me = this;
var records = _.map(data, function(record) {
//Calculations, etc.
console.log(record.get('c_TimeCriticalitySizing'));
var timecritsize = record.get('c_TimeCriticalitySizing');
//console.log(typeof timecritsize);
var mystr = "No decay";
var jobsize = record.get('JobSize');
var rroe = record.get('RROEValue');
var userval = record.get('UserBusinessValue');
var timecrit = record.get('TimeCriticality');
// Check that demoniator is not 0
if ( record.get('JobSize') > 0){
if (timecritsize === mystr){
var priorityScore = (timecrit + userval + rroe) / jobsize;
return Ext.apply({
c_wsjf: Math.round(priorityScore * 10) / 10
}, record.getData());
}
}
else{
return Ext.apply({
c_wsjf: 0
}, record.getData());
}
});
// Add the grid
me.add({
xtype: 'rallygrid',
showPagingToolbar: true,
showRowActionsColumn: true,
enableEditing: true,
store: Ext.create('Rally.data.custom.Store', {
data: records
}),
// Configure each column
columnCfgs: [
{
xtype: 'templatecolumn',
text: 'ID',
dataIndex: 'FormattedID',
width: 100,
tpl: Ext.create('Rally.ui.renderer.template.FormattedIDTemplate')
},
{
text: 'WSJF Score',
dataIndex: 'c_wsjf',
width: 150
},
{
text: 'Name',
dataIndex: 'Name',
flex: 1,
width: 100
}
]
});
}
});
// END OF APP CODE
The app works great until I add the if (timecritsize === mystr) conditional.
I also use console.log() to check that I've set all values for timecritsize to "No decay"

ArcGis javascript api 3.5 how to set visibility of a feature layer

i am using ArcGis javascript api 3.5 and my code is
map = new esri.Map("mapDiv", {
basemap: "streets",
center: [-112.07102547942392, 46.75909704205151],
zoom: 12,
slider: false,
infoWindow: infoWindow
});
var featureLayer = new esri.layers.FeatureLayer("http:/abc/arcgis/rest/services/MTARNG/MapServer/1", {
mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
infoTemplate: templateFuze,
outFields: ["*"]
});
var featureLayer1 = new esri.layers.FeatureLayer("http://abc/arcgis/rest/services/MTARNG/MapServer/0", {
mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
infoTemplate: templateParcel,
outFields: ["*"]
});
var featureLayer2 = new esri.layers.FeatureLayer("http://abc/arcgis/rest/services/MTARNG/MapServer/2", {
mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
infoTemplate: templateGrid,
outFields: ["*"]
});
Ext.create('Ext.form.Panel', {
width: 400,
height: 600,
bodyPadding: 10,
renderTo: Ext.get('LayerDiv'),
items: [{
xtype: 'checkboxgroup',
columns: 1,
vertical: true,
items: layerInfo,
listeners: {
change: {
fn: function (checkbox, checked) {
for (var i = 0; i < checkbox.items.items.length; i++) {
if (checkbox.items.items[i].checked) {
//visible true checkbox.items.items[0].boxLabel
}
else {
//visible false
}
}
}
}
}
}]
});
});
So i am trying to set the visibilty of the layer but i am not able to do. after that how to refresh the map ?
I got some function but it is working e.g.- visibleAtMapScale = false,
defaultVisibility = false and for refreshing i got only map.resize=true;
What else i can try to achive this functionality.
You can change the visibility of an layer using the hide() and show() functions - FeatureLayer inherits them from GraphicsLayuer (Which inherits them from Layer). So in your example, given featureLayer is a global variable it should be in scope when the event fires so you could just do:
featureLayer.hide();
and
featureLayer.show();
You don't need to refresh the map, it will happen automatically.
Simon
When creating a new FeatureLayer, you can specify the default visibility using the optional parameters. The default is true.
var featureLayer = new esri.layers.FeatureLayer("http:/.../MapServer/1",
{visible:false}
});
To set the visibility of the existing layer, you can use the setVisibility() method.
featureLayer.setVisibility(false);
If you want to enable intellisense support in Visual Studio you can download and reference the code assist plugin from the Esri website. There is a help page about it here with links to the various versions supported and how to use it from VS.
If you just want to get the VS2012 version for v3.5 of the JS API it is here and to reference it:
If working in an HTML file, add a script tag to add a reference to the code assist
<script type='text/javascript' src='path_to_vsdoc.js'></script>
If working in a JavaScript file, add a reference directive to the VSDoc file:
/// <reference path="~/Scripts/esri-jsapi-vsdoc.js" />

FullCalendar and Flot Resize Conflict

I've successfully integrated both a Flot line graph and an instance of FullCalendar into my site. They are both on separate pages (although the pages are loaded into a div via AJAX).
I've added the Flot Resize plugin and that works perfectly, re-sizing the line graph as expected. However, it seems to cause an error when resizing the calendar.
Even if I load the calendar page first, when I resize the window I get this error in the console (also, the calendar does not resize correctly):
TypeError: 'undefined' is not an object (evaluating 'r.w=o!==c?o:q.width()')
I was struggling to work out where the error was coming from, so I removed the link to the Flot Resize JS and tried again. Of course the line graph does not resize, but when resizing the calendar, it works correctly.
The div containers for the two elements have different names and the resize function is called from within the function to draw the line graph (as required).
I have tried moving the link to the Flot Resize plugin into different places (i.e. above/below the fullCalendar JS, into the template which holds the graph), but all to no avail.
Does anyone have any idea where the conflict might be and how I might solve it??
Thanks very much!
EDIT: It seems that the error is also triggered when loading the line graph (flot) page AFTER the fullcalendar page even without resizing the window.... Now I am very confused!
EDIT 2: The code which draws the line graph. The function is called on pageload and recieves the data from JSON pulled off the server. When the graph is loaded, I still get the error about shutdown() being undefined.
function plotLineGraph(theData){
var myData = theData['data'];
var myEvents = theData['events'];
var myDates = theData['dates'];
var events = new Array();
for (var i=0; i<myEvents.length; i++) {
events.push(
{
min: myEvents[i][0],
max: myEvents[i][1],
eventType: "Calendar Entry",
title: myEvents[i][2],
description: myEvents[i][3]
}
);
}
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': 'black',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length == 0) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
if(item.series.label != null){
showTooltip(item.pageX, item.pageY,
item.series.label + " of " + y);
}
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
var d1 = [
myData[0], myData[1], myData[2], myData[3], myData[4],
myData[5], myData[6], myData[7], myData[8], myData[9],
myData[10], myData[11], myData[12], myData[13], myData[14],
myData[15], myData[16], myData[17], myData[18], myData[19],
myData[20], myData[21], myData[22], myData[23], myData[24],
myData[25], myData[26], myData[27], myData[28], myData[29]
];
var markings = [
{ color: '#FFBDC1', yaxis: { from: 0, to: 2 } },
{ color: '#F2E2C7', yaxis: { from: 2, to: 3.5 } },
{ color: '#B6F2B7', yaxis: { from: 3.5, to: 5 } }
];
$.plot($("#placeholder"), [
{label: "Average Daily Rating", data: d1, color: "black"}
], {
events: {
data: events,
},
series: {
lines: { show: true },
points: { show: true }
},
legend: { show: true, container: '#legend-holder' },
xaxis: {
ticks:[
myDates[0], myDates[1], myDates[2], myDates[3], myDates[4],
myDates[5], myDates[6], myDates[7], myDates[8], myDates[9],
myDates[10], myDates[11], myDates[12], myDates[13], myDates[14],
myDates[15], myDates[16], myDates[17], myDates[18], myDates[19],
myDates[20], myDates[21], myDates[22], myDates[23], myDates[24],
myDates[25], myDates[26], myDates[27], myDates[28], myDates[29]
],
},
yaxis: {
ticks: 5,
min: 0,
max: 5
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] },
hoverable: true,
clickable: true,
markings: markings
},
selection: {
color: 'white',
mode: 'x'
},
});
$('#placeholder').resize();
$('#placeholder').shutdown();
}
EDIT 3:
The calendar is called like this:
function showCalendar() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#fullcalendar').fullCalendar({
header: {
left: 'prev',
center: 'title',
right: 'next'
},
clickable: true,
firstDay: 1,
eventSources: [
{
url: '/populate-calendar/{{theProductUuid}}/',
color: 'black',
data: {
text: 'text'
}
}
],
eventClick: function(calEvent, jsEvent, view) {
var startDate = $.fullCalendar.formatDate(calEvent.start, 'yyyy-MM-dd');
var endDate = $.fullCalendar.formatDate(calEvent.end, 'yyyy-MM-dd');
var eventId = calEvent.uuid;
$('#modal-event-title').text(calEvent.title);
$('#edit-event-name').val(calEvent.title);
$('#edit-start-date').val(startDate);
$('#edit-end-date').val(endDate);
$('#edit-event-text').val(calEvent.text);
$('#edit-event-btn').attr('data-uuid', eventId);
$('#modal-edit-event').on('click', '#delete-btn', function(){
deleteCalendarEvent(eventId);
});
$('#modal-edit-event').modal();
},
});
}
The AJAX to load the page containing the flot chart:
function loadDetailedReports(uuid){
$('#product-content').fadeOut('slow', function(){
$('#product-content').empty();
$('#whole-product-sub-nav .active').removeClass('active');
$('#detailed-reports-content').load('/detailed-reports/' + uuid + '/', function(){
$('#detailed-reports-btn').addClass('active');
$('#detailed-reports-content').fadeIn('slow', function(){
if (authorized){
setLocationHash('loadDetailedReports&' + uuid);
getChartData(uuid);
} else {
setLocationHash('');
}
});
});
});
}
And the AJAX to load the page containing the calendar:
function loadCalendar(uuid){
$('#detailed-reports-content').empty().hide();
$('#product-content').fadeOut('slow', function(){
$('#whole-product-sub-nav .active').removeClass('active');
$('#product-content').load('/calendar/' + uuid + '/', function(){
$('#calendar-btn').addClass('active');
$('#product-content').fadeIn('slow', function(){
if (authorized){
setLocationHash('loadCalendar&' + uuid);
} else {
setLocationHash('');
}
showCalendar();
});
});
});
}
The calls to .resize and .shutdown are there because I was under the impression that they are necessary to achieve the resizing function and in response to your earlier comment regarding shutdown...... They're quite possibly n00b errors........?!?!
It looks like this is triggering on line 198 of jquery-resize:
data.w = w !== undefined ? w : elem.width();
This sounds like a race-condition stemming from the way you load different content into the same div. Flot binds the resize event to the chart div, and only un-binds it if the plot is destroyed cleanly.
EDIT: Looking at your code, my first suggestion would be to get rid of the resize and shutdown calls at the end of plotLineGraph. The resize plugin doesn't require any setup; it hooks into Flot to attach automatically to any new plot. So your call to resize is actually to jQuery's resize event trigger, which may be what's causing the error.
EDIT #2: I'm still not clear on your structure, but to generalize: anywhere that you might be getting rid of #placeholder (via emptying its parent or anything like that) you should first call shutdown on the plot object. If you aren't keeping a reference to it, you can do it like this: $("#placeholder").data("plot").shutdown(); but then have to account for the fact that it's undefined prior to the creation of your first plot.
If that still doesn't work, I'd need to see a live (simplified) example to make any further suggestions.

Sencha Touch 2 Get Current Location on Button Click

I have a toolbar button which when clicked should update my map to my current location. I am unable to find a working example of this functionality and hoping someone can advise me. Please see below for sample code - thanks for your help
Map:
Ext.define('MyApp.view.Myap', {
extend: 'Ext.Map',
alias: 'widget.mymap',
config: {
useCurrentLocation: false,
mapOptions:{
zoom: 9,
center: new google.maps.LatLng(42.2, -72.5),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
listeners: {
maprender : function(comp, map){
google.maps.event.addListenerOnce(map, "idle", function () {
var host = window.location.origin ? window.location.origin : window.location.protocol + "/" + window.location.host;
var kmlOptions = {preserveViewport: false}
var now = +new Date();
var layer = new google.maps.KmlLayer(host + '/path/to.kml?timestamp=' + now, kmlOptions);
layer.setMap(map);
return layer;
});
},
}
},
})
Toolbar Button:
Ext.define('MyApp.view.btnLocateMe', {
extend: 'Ext.Button',
alias: 'widget.btnlocateme',
config: {
ui: 'normal',
iconCls: 'locate',
iconMask: true,
text: 'Locate Me',
listeners: [
{
fn: 'onButtonTap',
event: 'tap'
}
]
},
onButtonTap: function(button, e, options) {
//Produces error: cannot call method of undefined
currentLocation: new google.maps.LatLng(this._geo.getLatitude(), this._geo.getLongitude());
MyApp.view.MyMap.map.setCenter(currentLocation);
}
});
my two cents contribution, try this
1) in MyApp.view.Myap substitute
useCurrentLocation: false,
by
useCurrentLocation : {
autoUpdate : false
},
Also you should declare currentLocation as a variable (I presume)
var currentLocation = ...
This should works. I've use a similar logic as yours in onButtonTap but inside a controller with no problems
Best regards
I have one suggestion.
Try changing current location to
new google.maps.LatLng( this.geo.getLatitude(),this.geo.getLongitude() ) ;
I think you can gather more info from this question in here.
The simplest way - switch to the another map view with option useCurrentLocation: true set in the config