I am using FullCalendar library to load events in my calendar from Google Calendars. And the Calendar does display the events, but now I want to be able to delete/remove an event that sync with the google calendar. I am looking couple of days now how to do it, but can’t find the answer.
(I know there a couple of people who had the same problem but it doesn’t work for me)
I hope someone can help me find the solution.
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list', 'bootstrap', 'googleCalendar'],
customButtons: {
myCustomButton: {
text: 'custom!',
click: function() {
alert('clicked the custom button!');
}
}
},
header: { right: 'prev,next today,list,dayGridDay,timeGridWeek,dayGridMonth', left: 'prev,next today myCustomButton' }, // buttons for switching between views
defaultView: 'timeGridWeek',
themeSystem: 'bootstrap',
editable: true,
eventLimit: true,
eventRender: function(eventObj, el) {
},
// Showing events
events: {!! json_encode($events) !!},
});
calendar.render();
});
This is how I load the events:
$request->validate([ 'calendar_id' => 'required', ]);
$gclient = new Gclient; $client = $gclient->client();
$cal = Calendar::find($request['calendar_id']);
$client->setAccessToken($cal->gmail->token);
$gcal_id = isset($cal->calendar_id) ? $cal->calendar_id : env('GOOGLE_DEFAULT');
$g_cal = new \Google_Service_Calendar($client);
$eventlist = $g_cal->events->listEvents($gcal_id)->getItems();
$events = [];
foreach ($eventlist as $event) {
if ($event->summary == NULL ) {
if ($event->location == NULL ) {
$title = 'default';
}
else {
$title = $event->location;
}
}
else {
$title = $event->summary;
}
$events[] = [
'title' => $title,
'start' => $event->start->dateTime,
'end' => $event->end->dateTime,
'id' => $event->id
];
}
Related
I'm using FC 6 (upgrading from FC 3). I'm trying to load my events from my MS SQL Server database and JSON file but I don't understand why it's not working.
This is the call I made in my calendar.js:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
/*CODE*/
events: [{
url: '../script/apps/calendar/load.php',
method: 'POST',
},
{
url: '../../resource/various/vacation.json'
},
{
id: "weekend",
rrule: {
freq: 'weekly',
byweekday: [ 'sa', 'su' ],
dtstart: '2022-01-01',
},
allDay: true,
display:"background",
backgroundColor: "#90ee90"
}
],
But I'm not understanding why I cannot see any events on my calendar.
This is my load.php:
<?php
require_once "../../connection.php";
$data = array();
$query= sqlrsv_query($conn,"SELECT * FROM gestioneOre ORDER BY idAssenza");
while($result = sqlrsv_fetch_array($query)){
$data[] = array(
'idAssenza' => $result['idAssenza'],
'title' => $result['ename'],
'start' => $result['starts'],
'end' => $result['ends'],
'nomeUtente'=> $result['nomeUtente'],
'pausaPranzo'=> $result['pausaPranzo']
);
}
echo json_encode($data);
?>
I change by myself the JSON with an old one I had and now it's working again; but now i'ts not loading the weekends and the one from the database.
JSON send it from my database ->
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"]
);
}
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.
I dont know how update or delete fullcalendar events on my symfony project.
To add a new event, i open a modal window with a form to submit a new event and insert it in my database.
This is my controler(it work fine):
$datas = array();
$form = $this->createFormBuilder($datas)
->add('title', TextType::class)
->add('startDate', TextType::class, array(
'attr'=> array('class' => 'dateTimePicker')))
->add('endDate', TextType::class, array(
'attr'=> array('class' => 'dateTimePicker')))
->add('backgroundColor', ChoiceType::class, array('choices' => $color ))
->getForm();
$form->handleRequest($request);
/** Création d'un nouvel évenement */
if ($form->isSubmitted() && $form->isValid()) {
$title = $form->get('title')->getData();
$start = new \DateTime($form->get('startDate')->getData());
$end = new \DateTime($form->get('endDate')->getData());
$backgroundColor = $form->get('backgroundColor')->getData();
$event = new CalendarEvent();
$event->setTitle($title);
$event->setStartDate($start);
$event->setEndDate($end);
$event->setBackgroundColor($backgroundColor);
$em = $this->getDoctrine()->getManager();
$em->persist($event);
$em->flush();
return $this->redirect($this->generateUrl('ma_lrm_accueil'));
}
I know that to update events, i have to have a javascript like this:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev, next',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
timezone: ('Europe/London'),
businessHours: {
start: '09:00',
end: '18:30',
dow: [1, 2, 3, 4, 5]
},
allDaySlot: true,
defaultView: 'agendaWeek',
lazyFetching: true,
firstDay: 1,
selectable: true,
/*timeFormat: {
agenda: 'h:mmt',
'': 'h:mmt'
},*/
editable: true,
eventDurationEditable: true,
events: 'http://localhost/ligne_rh/web/app_dev.php/admin/accueil/calendar',
eventResize: function(events) {
console.log("Entrée dans : eventResize");
var start1 = events.start.format('Y-m-d\TH:i:s');
var end1 = events.end.format('Y-m-d\TH:i:s');
var xhr = $.ajax({
type: "POST",
url: 'http://localhost/.../calendar/event/update',
data: 'title=' + events.title + '&start=' + start1 + '&end=' + end1 + '&id=' + events.id,
dataType: 'html',
success: function(data) {
window.location.reload(true);
},
error: function() {
alert("...");
},
});
},
});
I dont understand any of it and i have no idea what my controler should look like.
Please HELP ME with an example!! I am novice!! thank you!!!!
You should use
$em->merge($event);
for updating already existing entity and
$em->remove($event);
for removing entity.
Also maybe you should try to create different controller actions(eventDeleteAction, eventCreateAction) to make CRUD operations.
Hi you can use https://github.com/tattali/CalendarBundle the documentation explain how to link the calendar to a CRUD to allow create, update and delete events
On the first load of the page, it shows a single event per day, but on the second load (or refresh of the page) it adds a duplicate event on the same day in the full calendar.
Here is my code:
var CalendarView = Backbone.View.extend({
el : '#calendar-box',
initialize : function() {
// TODO for instance: more instances, Event Bus bindings... only once.
this.calendarModel = new CalendarModel();
$('#calendar-box').hide();
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
this.calendarModel.fetch({
success : function(model, response, options) {
$.unblockUI();
var count=0;
var eventsList=[];
model.attributes.result.forEach(function(){
eventsList.push({
id: model.attributes.result[count].eventId,
title:model.attributes.result[count].title,
start: new Date(model.attributes.result[count].startDate),
end: new Date(model.attributes.result[count].endDate),
attorneyName: model.attributes.result[count].attorneyName,
codeLitOrg: model.attributes.result[count].codeLitOrg,
balance: model.attributes.result[count].balance,
litCode: model.attributes.result[count].litCode
});
count++;
});
if (!_.isEmpty(eventsList)){
$('#calendar').fullCalendar({
editable: true,
events: eventsList,
eventMouseover: function(event, jsEvent, view) {
var info = event.title+'\nBK/LIT: '+event.codeLitOrg+'\nBalance: '+event.balance
+'\nAttorney: '+event.attorneyName+'\nLitCode: '+event.litCode;
$(jsEvent.target).attr('title', info);
},
theme: false,
height:575,
weekMode:'liquid',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
});
}
},
error : function(model, xhr, options) {
$.unblockUI();
}
});
$.eventBus.on('calendarModalLoaded',function(){
if (!($('.fc-border-separate').html())){
$('#calendar').fullCalendar('today');
}
});
},
render : function() {
// TODO for instance, bindings elements after ready in DOM.
$('#calendar').fullCalendar('today');
return this;
},
events : {
'click a.op-attorney-info' : 'onAttorneyInfo',
'click .go-back-link' : 'goBack'
},
goBack: function(){
$('#calendar-box, .content-box').toggle();
//$('.content-box').toggle();
//$('.go-back-link').hide();
},
onAttorneyInfo : function(ev) {
// TODO for instance, fetch attorney's model
}
});
return CalendarView;
});
I have tried $('#calendar').fullCalendar('removeEvents'), but it is also not working.
Please help me out.