How to get the start and end time to full calendar - javascript

I need to get the start time and the end time of the even I have saved in the database,
I was able to get the start date and end date from the start_date & end_date fields from the database and display it in the full calendar as shown in the below image
But I need to get the times too from the database from the fields start_time & end_time
Here's how my database fields looks like
I just need to know how can I display the time range as the date range here
Here's my scripts
<script>
$(document).ready(function() {
$(".dashbord-body").removeClass("bg-white");
});
$(function() {
$('#calendar').fullCalendar({
selectable:true,
height:650,
showNonCurrentDates:false,
editable:false,
defaultView:'month',
yearColumns: 3,
header: {
left: 'prev,next', //note no "buttons
center: 'title',
right: 'year,agendaDay,agendaWeek,month,timelineCustom'
},
eventSources: [
{
url: '/calendar', // use the `url` property
color: 'red', // an option!
textColor: 'white', // an option!
}
],
eventDataTransform: function(eventData) {
return {
title: eventData.name,
start: eventData.start_date,
end: eventData.end_date
}
},
});
});
</script>
HTML
<div id='calendar'></div>
Controller function
public function calendar()
{
$calendar= Event::latest()->get();
return response()->json($calendar);
}

I was able to fix the issue I faced here by below codes in my controller function
public function calendar(Job $job)
{
$user = auth()->user();
$calendar = $job->where('user_id',$user->id)->get();
$calendar = $calendar->map(function ($post) {
$post['start'] = $post->start_date . ' ' . $post->start_time;
$post['end'] = $post->end_date . ' ' . $post->end_time;
// unset($post['name']);
return $post;
});
return response()->json($calendar);
}
And added the extra field name to the Model as below code
protected $visible = ['start','end'];

Related

Loading events using a function in FullCalendar

I'm using ExtJS 3.4 and fullcalendar#5.10.2 ( using jsdelivr CDN ).
My config Object :
var config = {
events : eventsLoader,
initialView: 'dayGridMonth',
height : 500,
nowIndicator : true ,
editable: false,
locale : "fr",
showNonCurrentDates: false,
headerToolbar: {
right: 'dayGridMonth,timeGridWeek,timeGridDay list',
center: 'title',
left: 'today prev,next'
},
footerToolbar: {
right: "prevYear,nextYear"
},
buttonText : {
today: "Aujourd'hui",
month: 'Mois',
week: 'Semaine',
day: 'Jour',
list: 'Liste'
}
}
The eventsLoader function :
var eventsLoader = function(fetchInfo, successCallback, failureCallback) {
Ext.Ajax.request({
url : gpao.OF.url,
method : "POST",
params : {
action : 'getEvents',
idCentreDeCharge : id,
},
success : function(result,response) {
var jsonData = Ext.util.JSON.decode(result.responseText);
var jsonRes = jsonData.results;
var events = jsonRes.map(function(eventEl) {
return {
title : eventEl.title,
start : eventEl.start,
end : eventEl.end
}
})
console.log("events : ",events);
successCallback(events);
},
failure : function() {
console.error('there was an error with the Ajax request to '+gpao.CentreCharge.url);
failureCallback("failed");
}
});
}
The fetchInfo object :
var now = new Date();
var startDate = new Date();
startDate.setYear(now.getFullYear() - 3);
var endDate = new Date();
endDate.setYear(now.getFullYear() + 3);
var fetchInfo = {
start : startDate.toISOString().split('T')[0],
end : endDate.toISOString().split('T')[0]
}
console.log("fetchInfo : ",fetchInfo);
Example of the events array passed to successCallback(events) looks like this :
I used a dummy events array just to test, and my calendar renders with no errors.
The Problem :
I'm rendering the calendar on a Tab Panel, this time using a function instead of a dummy array, the first time a user selects it the calendar looks all messed up ( week days all clummed up in the top left corner on top of each other ), untill i either resize the page CTRL + MouseWheel, switch views, or click any button like prev,next,prevYear,nextYear,today, i'm stuck on this, any help appreciated.
If you are hiding the container in which the calendar element belongs, then you need to call the calendar's render() method when you re-display it, otherwise it can be messed up by being in a hidden container.

Pass another parameter to Fulcalendar

Here is the code, the "events: url," part of the code is coming through into my fullcalendar.js file and adds the events however I also want to add a list of users from json data like so users:'urlusers'
Will I have to edit the fullcalendar.js file and if so where can I add another parameter for the users.
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
defaultView: 'agendaWeek',
minTime: "08:00:00",
maxTime: "20:00:00",
editable:false,
header:{
left:'prev,next today',
center:'title',
},
events: 'https://events.com/eventsjson',
users:'https://events.com/usersjson',
selectable:true,
selectHelper:true,
select: function(start, end, allDay)
{
var titlestart = $.fullCalendar.formatDate(start, "DD-MM-Y HH:mm:ss");
var r = confirm("Request Time " + titlestart);
if (r == true) {
event.preventDefault();
//Open dialog
var subject = 'Booking '+titlestart;
var emailBody = 'Create booking for '+titlestart
showDialog(titlestart);
} else {
}
},
});
});
Not the solution I was thinking of but got the result.
on the events: 'https://events.com/eventsjson', I needed to add more data to the JSON then the fullcalendar sorted the rest out for me
foreach($result as $row)
{
$data[] = array(
'id' => $row["user_id"],
'start' => $row["startevent"],
'end' => $row["endevent"],
'backgroundColor' => $row["backgroundColor"],
'borderColor' => $row["borderColor"]
);
}

Displaying data on Full Calendar using Ajax not displaying records

I have created a Full Calendar and using ajax to populate the events from a database tables.
I can get the graph showing however it isn't populating the events from the database, instead it is showing todays date and time and only one event.
I'm not sure what I'm doing wrong.
I'm following this tutorial:
http://www.dotnetawesome.com/2017/06/event-calendar-in-aspnet-mvc.html
What is
currently displaying
Script which is in my Layout page
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Calendar/Schedules",
success: function (data) {
$.each(data, function (i, v) {
events.push({
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.EndTime != null ? moment(v.EndTime) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events
})
}
});
</script>
Get method under the Calendar Controller
public JsonResult Schedules()
{
var schedules = _context.Schedules.ToList();
var result = new JsonResult(new { Data = schedules});
return new JsonResult(result.Value);
}
however it isn't populating the events from the database
Note that you're following an old tutorial for ASP.NET Classic instead of ASP.NET Core. And the way we return a JsonResult has changed:
public JsonResult Schedules()
{
var schedules = _context.Schedules.ToList();
var result = new JsonResult(new { Data = schedules});
return new JsonResult(result.Value);
return new JsonResult(schedules);
}
Today we don't need specifiy a Data property for JsonResult anymore. Instead, simply construct a JsonResult by new JsonResult(the_data).
The second issue is, the returned json by default is Camel-Cased if you're using ASP.NET Core 3.1. However, it's likely that your javascript code assumes that the JSON returned by server is Pascal-Cased. If that's the case, change your js code as below:
events.push({
title: v.Subject,
title: v.subject,
description: v.Description,
description: v.description,
start: moment(v.Start),
start: moment(v.start),
end: v.EndTime != null ? moment(v.EndTime) : null,
end: v.endTime != null ? moment(v.endTime) : null,
color: v.ThemeColor,
color: v.themeColor,
allDay: v.IsFullDay
allDay: v.isFullDay
});

Fullcalendar refetch eventsource

As the title says, I have a question regarding EventSource in the fullcalendar.
At the moment I can load 1 google calendar in the fullcalendar. And know how to add multiple google calendars.
However, I want to use checkboxes (linked to their own google calendar), I dynamically create an array with the googleCalendarIds, all this works, but I can't get the calendar to "refetch" all the event from the google calendars in the array.
At the moment, this is the code I use to populate the calendar:
document.addEventListener('DOMContentLoaded', function() {
var selected = [];
$('.badgebox:checked').each(function() {
selected.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
});
$('.badgebox').on('click', function() {
if($(this).prop('checked')) {
selected.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
$('#calendar').fullCalendar('refetchResources');
}else{
index = selected.findIndex(obj => obj.googleCalendarId === $(this).val());
selected.splice(index, 1);
$('#calendar').fullCalendar('refetchResources');
}
});
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
header: {
center: 'dayGridMonth,timeGridWeek'
},
views: {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }
}
},
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap', 'googleCalendar' ],
googleCalendarApiKey: 'api key',
eventSources: selected,
eventClick: function(info) {
info.jsEvent.preventDefault();
},
defaultView: 'timeGridWeek',
weekNumbers: true,
locale: 'nl',
themeSystem: 'bootstrap',
nowIndicator: true
});
calendar.render();
});
But what I am getting is an error:
TypeError: $(...).fullCalendar is not a function
I have loaded all the files needed (and can see they are loaded).
Edit current code
This is the code I use now, but still not sure how to fix the resources part (refreshing):
document.addEventListener('DOMContentLoaded', function() {
var curSource = [];
$('.badgebox:checked').each(function() {
curSource.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
});
var newSource = [];
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'key',
header: {
center: 'dayGridMonth,timeGridWeek'
},
views: {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }
}
},
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap', 'googleCalendar', 'resourceTimeGrid', 'resourceDayGrid' ],
googleCalendarApiKey: 'apikey',
eventSources: curSource,
eventClick: function(info) {
info.jsEvent.preventDefault();
},
defaultView: 'timeGridWeek',
weekNumbers: true,
locale: 'nl',
themeSystem: 'bootstrap',
nowIndicator: true
});
$('.badgebox').on('change', function() {
if($(this).prop('checked')) {
newSource.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
}else{
index = newSource.findIndex(obj => obj.googleCalendarId === $(this).val());
newSource.splice(index, 1);
}
curSource = newSource;
calendar.getEventSources().forEach(eventSource => {
eventSource.remove()
});
calendar.addEventSource(curSource);
});
calendar.render();
});
Any idea?
Your logic for adding and removing event sources is flawed - it'll remove all the previous sources, but only ever add the currently selected one (well, except that you never clear newSource so it'll contain all sorts of duplication after a while). The other problem is that when you write calendar.addEventSource(curSource); you're adding an array of event sources (even though it only ever contains one item) but adding it as if it was a single event source object. Therefore it's not in the format fullCalendar expects, so it doesn't add anything.
Instead you can just use the same logic you use when you first declare the calendar, to loop through all the currently selected checkboxes and set all of them as the current sources. This is the simplest way to do it. Just move that logic into a function so you can re-use it. It also removes the necessity for global objects containing the list of sources. Something like this:
function getEventSources() {
var sources = [];
$(".badgebox:checked").each(function() {
sources.push({
id: $(this).val(),
'googleCalendarId' : $(this).val(),
className: $(this).data("color")
});
});
return sources;
}
Then in the calendar config, set the initial event sources by calling the function:
eventSources: getEventSources(),
And handle the "change" event on the checkboxes like this:
$(".badgebox").on("change", function() {
//remove event sources
calendar.getEventSources().forEach(eventSource => {
eventSource.remove();
});
//get currently selected sources
var sources = getEventSources();
//add each new source to the calendar
sources.forEach(eventSource => {
calendar.addEventSource(eventSource);
});
});
I made a live demo here: https://codepen.io/ADyson82/pen/Jjoovym. I couldn't use google calendars for the demo obviously so I've done it with hard-coded lists of events, but the overall logic of the process is identical.

fullCalendar.js defaultView: 'agendaDay' shows events in all-Day section

Using fullCalendar.js with defaultView as agendaDay, and getting events as JSON from mysql. The ERROR is that it shows the events in the 'all-Day' section.
I tried this:
eventRender: function(event, element, view) {
if (event.allDay == 1) {
event.allDay = true;
} else {
event.allDay = false;
}
I also tried:
eventRender: function(event, element, view) {
event.allDay = false;
},
and also this:
eventAfterAllRender: function(event, element, view) {
event.allDay = false;
},
But I'm stock, still not working.
Here is a WORKING fiddle without JSON: events:
http://jsfiddle.net/sebababi/g5gtG/1/
To test, you need to change the event: in the jsFiddle for: events: "events.php",
Here is the events.php file
<?php
// List of events
$json = array();
// Query that retrieves events
$requete = "SELECT * FROM evenement ORDER BY id";
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
and here is the mysql table
CREATE TABLE `evenement` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_bin NOT NULL,
`start` datetime NOT NULL,
`end` datetime DEFAULT NULL,
`url` varchar(255) COLLATE utf8_bin NOT NULL,
`allDay` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=34 ;
INSERT INTO `evenement` (`id`, `title`, `start`, `end`, `url`, `allDay`) VALUES
(24, 'testing defaultView with agendaDay and JSON event', '2014-01-07 08:30:00', '2014-01-07 09:30:00', '', 1);
Any help to get me on the right track would be greatly appreciated.
Ok i added some code to your JsFiddle to show buttons prev,next:
HTML
<input type="button" value="prev" id="prevbutton" />
<input type="button" value="next" id="nextbutton"/>
<div id='calendar'></div>
JS
var calendar = $('#calendar').fullCalendar({
defaultView: 'agendaDay',
header: {
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
year: 2014,
month: 0,
day:7,
buttonText: {
prev: '<',
next: '>'
},
events: [
{
title: 'testing defaultView with agendaDay and JSON event',
start: '2014-01-07 11:00',
allDay: false
}
]
});
$('#prevbutton').click(function() {
calendar.fullCalendar('prev');
});
$('#nextbutton').click(function() {
calendar.fullCalendar('next');
});
Now for your JSON you have to manage in your PHP to get the json string like this
[{"id":"24","title":"testing with defaultView: agendaDay, not showing in Day","start":"2014-01-09 08:30:00","end":"2014-01-09 09:30:00","url":"","allDay":false}]
Use
var_dump(json_decode($json));
to see if your string is correct, and you must convert the 0 and 1 values for allDay from DATABASE in your PHP not in client side.
EDIT
Following the bellow conversation...
You misunderstood my point Sebastian that was for you to get contents of PDO::FETCH_ASSOC in PHP and convert that into a normal PHP associative array and it would be in this fase of conversion when building the normal PHP array that you would change the value of allDay.
Based on that link you could access the returned row that is in fact an associative array like we all know from PHP and change allDay value from 0 to false for example.
Only then you would use json_encode() and send it back to fullcalendar.

Categories