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.
Related
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'];
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
});
Show events in the calendar after the loading screen.
events: {
JSON.parse(get_data());
},
CONTROLLER all is ok no problem here expept for the JSON.PARSE
$calendar = array();
foreach($data_calendar as $key => $val) {
$calendar[] = array(
'id' => intval($val - > id),
'title' => $val - > title,
'description' => trim($val - > description),
'start' => date_format(date_create($val - > start_date), "Y-m-d H:i:s"),
'end' => date_format(date_create($val - > end_date), "Y-m-d H:i:s"),
'color' => $val - > color,
);
}
$data = array();
$data['get_data'] = json_encode($calendar);
$data['telaativa'] = 'agenda'; //retorna agenda penso que manté menu barra esquerda colapsada em agenda
$data['tela'] = ('/calendario/view_agenda--');
view_agenda--
$this - > load - > view('view_home2', $data);
RESULT id with 1 or "1" in the result is because i declare intval for id so i can get both formats in output.
'get_data' => string '[{"id":1,
'get_data' => string '[{"id":"1",
array (size=3)
'get_data' => string '[{"id":1,"title":"teste evento1","description":"descri\u00e7\u00e3o do evento bla bla bla","start":"2019-05-06 00:00:00","end":"2019-05-07 00:00:00","color":"#0071c5"},{"id":6,"title":"cert soldador 1-1","description":"descrtivo do certificado ser 111 bw t1-25mm s275","start":"2019-05-29 23:00:00","end":"2019-05-30 00:00:00","color":"#40E0D0"},{"id":7,"title":"cert soldador 1-2 soldador nr1","description":"certificado de soldador nr 1 doc 1-2","start":"2019-05-30 00:00:00","end":"2019-05-31 00:00:00","color'... (length=5865)
'telaativa' => string 'agenda' (length=6)
'tela' => string '/calendario/view_agenda--' (length=25)
VIEW
$(document).ready(function() {
$('.date-picker').datepicker();
$('#calendarIO').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
defaultDate: moment().format('YYYY-MM-DD'),
editable: true,
eventLimit: true, // allow "more" link when too many events
selectable: true,
selectHelper: true,
select: function(start, end) {
$('#create_modal input[name=start_date]').val(moment(start).format('YYYY-MM-DD'));
$('#create_modal input[name=end_date]').val(moment(end).format('YYYY-MM-DD'));
$('#create_modal').modal('show');
save();
$('#calendarIO').fullCalendar('unselect');
},
eventDrop: function(event, delta, revertFunc) { // si changement de position
editDropResize(event);
},
eventResize: function(event, dayDelta, minuteDelta, revertFunc) { // si changement de longueur
editDropResize(event);
},
eventClick: function(event, element) {
deteil(event);
editData(event);
deleteData(event);
},
events: {
JSON.parse(get_data());
},
});
});
ERROR
SyntaxError: missing : after property id
If i delete JSON.parse(get_data()); my calendar will be visible but no events. If I add an event it will be shown until I refresh the page. All function work expect loading data from DB into the calendar.
You seem to be confused about how to use your PHP view data in your view.
I think maybe you should read this: https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view . It shows you how to inject the PHP data you provided to the view into your page.
What you're doing now is writing pure JavaScript which tries to call a function which doesn't exist. What you need to do is write a PHP snippet to inject the server-side data into the HTML and JavaScript code which the PHP is creating.
I'm not a CodeIgniter expert, but based on that documentation page, what I think you should be writing is:
events: <?php echo $get_data; ?>,
If you inject it like this without quote marks, then it will be automatically treated as JavaScript array literal, so there's no need for JSON.parse(). This works because JSON syntax is a subset of valid JavaScript object syntax. If you use the View Source feature in your browser to view the finished output of your page, you'll see what I mean.
(Note that you also need to remove the { and } from the events: declaration, because fullCalendar expects an array, not an object.
I need to filter the events that are displayed on the screen using a select. I am using .change to send the value of the selected option and the screen is refreshed, but I have not been successful.The events are displayed correctly if I remove the WHERE. I think the model is not getting the value of rut_usu. Any help is welcome.
Controller ( cCalendar )
public function geteventos(){
$rut_usu = $this->input->post('rut_jc');
$r = $this->mCalendar->geteventos();
echo json_encode($r, $rut_usu);
}
Model (mCalendar)
public function geteventos($rut_usu){
$this->db->select('CONCAT(estudiantes.pnombre," ", estudiantes.apellido_pa," ", estudiantes.apellido_ma,", ",motivos_citas.descripcion_mot) As title ,citas.id_ci id, citas.fecha_ini start, citas.fecha_ter end, citas.id_mot mot, CONCAT(estudiantes.pnombre," ", estudiantes.apellido_pa," ", estudiantes.apellido_ma) as estudiante');
$this->db->select('CONCAT(usuarios.pnombre," ", usuarios.apellido_pa," ", usuarios.apellido_ma) as jefe_c, estudiantes.rut_estu rut_estudiante');
$this->db->from('citas');
$this->db->join('estudiantes', 'citas.rut_estu = estudiantes.rut_estu');
$this->db->join('motivos_citas','citas.id_mot = motivos_citas.id_mot');
$this->db->join('usuarios','citas.rut_usu = usuarios.rut_usu');
$this->db->where('rut_usu',$rut_usu);
return $this->db->get()->result();
}
Javascript (send select value to filter events)
$("#rut_jc").change(function(){;
//rut_jc is the name of the select
var rut_usu = $("#rut_jc").val();
$.ajax({
url: "<?php echo base_url(); ?>" + "cCalendar/geteventos/",
type: 'post',
data: { "rut_jc": rut_usu },
success: function(response){
$("#calendar").fullCalendar('refetchEvents');
}
});
Javascript (show the events)
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
events: function(start, end, timezone, callback) {
$.post('<?php echo base_url(); ?>cCalendar/geteventos',
{ "start": start.format("YYYY-MM-DD"), "end": end.format("YYYY-MM-DD") },
function (data) {
callback($.parseJSON(data));
});
},
dayClick: function (date, jsEvent, view) {
date_last_clicked = $(this);
$('#modal_registrar').modal();
},
eventClick: function(event, jsEvent, view) {
$('#event_id').val(event.id);
$('#id_mot2').val(event.mot);
$('#nombre_estudiante').val(event.estudiante);
$('#jc2').val(event.jefe_c);
$('#rut_estudiante').val(event.rut_estudiante)
$('#start_f').val(moment(event.start).format('DD/MM/YYYY HH:mm:ss'));
$('#end_f').val(moment(event.end).format('DD/MM/YYYY HH:mm'));
$('#modal_editar').modal();
},
minTime: "08:30:00",
maxTime: "23:00:00"
});
when you run $("#calendar").fullCalendar('refetchEvents'); it runs another ajax call (the one defined in the calendar's events option), separate to the one you made explicitly from the "change" handler. You're throwing away the response from that call where you included rut_jc / rut_usu. You don't do anything with it. So it's no surprise it doesn't affect the calendar.
Instead of making a separate, meaningless ajax call, simply integrate this new functionality into your existing code:
Calendar Code
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listMonth'
},
defaultDate: new Date(),
navLinks: true, // can click day/week names to navigate views
businessHours: true, // display business hours
events: function(start, end, timezone, callback) {
$.post('<?php echo base_url(); ?>cCalendar/geteventos', {
"start": start.format("YYYY-MM-DD"),
"end": end.format("YYYY-MM-DD"),
"rut_jc": $("#rut_jc").val() //add the extra value to the existing filter parameters. fullCalendar can then use it directly.
},
function(data) {
callback($.parseJSON(data));
}
);
},
dayClick: function(date, jsEvent, view) {
date_last_clicked = $(this);
$('#modal_registrar').modal();
},
eventClick: function(event, jsEvent, view) {
$('#event_id').val(event.id);
$('#id_mot2').val(event.mot);
$('#nombre_estudiante').val(event.estudiante);
$('#jc2').val(event.jefe_c);
$('#rut_estudiante').val(event.rut_estudiante)
$('#start_f').val(moment(event.start).format('DD/MM/YYYY HH:mm:ss'));
$('#end_f').val(moment(event.end).format('DD/MM/YYYY HH:mm'));
$('#modal_editar').modal();
},
minTime: "08:30:00",
maxTime: "23:00:00"
});
Change handler for the <select>
$("#rut_jc").change(function(){;
$("#calendar").fullCalendar('refetchEvents');
});
Additionally, you weren't passing the $rut_usu value to your model (instead, you just sent it back in the response, which made no sense).
N.B. I have also taken the liberty of adding the start/end dates sent by fullCalendar into your controller and model. As I mentioned in my answer to your earlier question a few days ago, you now need to alter your database query with another WHERE clause to ensure it only returns events which start or end between these two dates (inclusive).
Controller
public function geteventos(){
$start = $this->input->post('start');
$end = $this->input->post('end');
$rut_usu = $this->input->post('rut_jc');
$r = $this->mCalendar->geteventos($start, $end, $rut_usu);
echo json_encode($r);
}
Model
public function geteventos($start, $end, $rut_usu){
//...etc
I have started using the fullcalendar plugin for a calendar display of mine.
The goal of the calendar is to allow the user to add events labled Accommodation or Canteen.
When my page loads, I use PHP to build an array that gets parsed to the JavaScript that displays the events.
What I would like to do is be able to display the Google Material Design icons with the matching event.
Accommodation will be the hotel icon.
Canteen will be the local dining icon.
Now in Google's documentation it shows that the icons can be applied using the following method:
<i class="material-icons">hotel</i>
However when passing events to the plugin, this does not seem to be possible.
The php where the array gets built:
$events = array();
while (!$result->eof()) {
if ($result->valueof('date_canteen_available') == 't') {
$events[] = array("title" => "Canteen", "start" => $result->valueof('date_date'));
}
if ($result->valueof('date_accommodation_available') == 't') {
$events[] = array("title" => "Accommodation", "start" => $result->valueof('date_date'));
}
Part of my javascript:
<script>
$('#calendarAccomo').fullCalendar({
header: {
},
defaultView: 'month',
editable: true,
selectable: true,
allDaySlot: false,
events: <?php echo json_encode($events) ?>,
</script>
My question is, how can I display the correct icon with each event entry?
You can do this:
$('#calendar').fullCalendar({
events: [{
title: 'Accommodation',
start: '2017-02-01',
description: 'This is a cool event'
}, {
title: 'Canteen',
start: '2017-02-02',
description: 'This is a cool event'
}],
eventRender: function(event, element, view) {
if (event.title == 'Accommodation') {
element.append('<i class="material-icons">hotel</i>');
} else {
element.append('<i class="material-icons">local_dining</i>');
}
}
});
Try the fiddle.