I try to show some events from database in my fullCalendar but it doesn't work? My app is on Symfony 3. First I installed the ancarebeca/fullcalendar, I followed the installation step by step and my agenda is here! In my controller, I have a method to return a JSON array like this:
[{"1":{"id":1,"title":"test","start":"2017-08-01
18:00:00","end":"2017-08-01
20:00:00","allDay":true,"editable":true,"startEditable":true,"durationEditable":true,"overlap":true,"url":"","backgroundColor":"","textColor":"","className":"","rendering":"","constraint":1,"source":"","color":""},"2":{"id":2,"title":"test2","start":"2017-08-02
15:00:00","end":"2017-08-02
16:00:00","allDay":true,"editable":true,"startEditable":true,"durationEditable":true,"overlap":true,"url":"","backgroundColor":"","textColor":"","className":"","rendering":"","constraint":1,"source":"","color":""}}]
If you want look my method:
public function loadAction()
{
//dump($calendarService);die();
$em = $this->getDoctrine()->getManager();
$evenements = $em->getRepository('MALrmBundle:CalendarEvent')->findAll();
$calendarService = $this->get('ma_lrm_bundle.service.listener');
$events = array();
foreach ($evenements as $key => $evenement)
{
$events[$evenement->getId()]=$calendarService->loadData($evenement);
}
$response = new JsonResponse($events);
return $response->setData(array($events));
}
At the end, in my js file, i just call the url, like this:
events: 'http://localhost/ligne_rh/web/app_dev.php/admin/accueil/calendar',
...But i have no return in my calendar...
i also post my full Js file:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev, next',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
timezone: ('Europe/London'),
businessHours: {
start: '09:00',
end: '17:30',
dow: [1, 2, 3, 4, 5]
},
allDaySlot: false,
defaultView: 'agendaWeek',
lazyFetching: true,
firstDay: 1,
selectable: true,
timeFormat: {
agenda: 'h:mmt',
'': 'h:mmt'
},
/*columnFormat: {
month: 'ddd',
week: 'ddd D/M',
day: 'dddd'
},*/
editable: true,
eventDurationEditable: true,
events: 'http://localhost/ligne_rh/web/app_dev.php/admin/accueil/calendar',
});
});
Please help me.
Your JSON is structured differently than it expects.
[{"1":{"title":"test","start":"2017-08-01 18:00"}}]
should be like
[{"title":"Title","test":"2017-08-01 18:00"}]
To fix, try changing
$events[$evenement->getId()]=$calendarService->loadData($evenement);
to
$events[]=$calendarService->loadData($evenement);
As an aside, I'm not familiar with Symphony but the return may be as easy as return $response;
since you already use $events in the $response = new JsonResponse($events);
or just return new JsonResponse($events);
Related
My event feed does only work when I hardcode the events in my EventController. Once I get them from database query the events are not displayed though the first event is the exact same I used in the hardcoded event.
Works (Calendar shows event):
public function eventFeed(Request $request)
{
$events = array(
[
"id" => 1,
"resourceId" => '1115',
"title" => 'Wartung Steuerung',
"start" => '2020-06-11 00:20:23',
"end" => '2020-06-28 21:21:30',
]
);
return json_encode($events);
}
From the calendar view I have a control Ajax call that fetches the same feed as FullCalendar. The received feed is
[{"id":1,"resourceId":"1115","title":"Wartung Steuerung","start":"2020-06-11 00:20:23","end":"2020-06-28 21:21:30"}]
Does not work (Calendar stays empty):
public function eventFeed(Request $request)
{
$start = Carbon::create($request->input('start'));
$end = Carbon::create($request->input('end'));
$events = DB::table('toolplanview')->select('id','resourceId','title','start','end')
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get();
return json_encode($events);
}
The feed from the DB query is:
[{"id":1,"resourceId":"1115","title":"Wartung Steuerung","start":"2020-06-11 00:20:23","end":"2020-06-28 21:21:30"},{"id":2,"resourceId":"1157","title":"Werkstatt","start":"2020-06-12 09:09:41","end":"2020-06-24 03:45:59"},{"id":3,"resourceId":"1136","title":"Neue Toranlage","start":"2020-06-10 20:29:44","end":"2020-06-23 04:26:38"},{"id":4,"resourceId":"1138","title":"Neue Toranlage","start":"2020-06-10 03:23:12","end":"2020-06-28 11:20:36"}]
I dont see why this feed would not work. My calendar:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
locale: 'de',
plugins: [ 'interaction', 'resourceTimeline' ],
defaultView: 'resourceTimelineWeek',
editable: true,
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' },
header: {
right: 'today prev,next'
},
slotLabelFormat: [
{ month: 'long', year: 'numeric' }, // top level of text
{ weekday: 'short', day: '2-digit' } // lower level of text
],
resources: 'http://localhost/matpro/public/resource-feed',
events: 'http://localhost/matpro/public/event-feed',
});
calendar.render();
});
I found the reason for this behaviour, the issue is the where clause of my DB query:
$events = DB::table('events')->select('id','resourceId','title','start','end')->get();
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get();
When calender e.g. displays a week from 01.06. to 08.06 and one of my (generally longer) events starts on 30.05. and ends on 05.06. this event won't be displayed due to the where clauses in my query. The example dates I picked for testing accidentally overlapped with the calender start or end and therefore did not show up.
I am using Laravel Datatables. I am successfully in loading data from a MySQL database through a query.
The problem I have is to be able to query the table by month by sending a month number. I am not able to successfully send a parameter containing the month number to my ajax function on the back end.
I tried many variations but nothing worked.
I get "Undefined index: month"
Here are my code snippets:
Javascript ajax:
<script>
$(function() {
var month = "<?= $brandData['month'] ?>"; // contains a month number
$('#accounts').DataTable({
processing: true,
serverSide: true,
type: "POST",
ajax: '{!! url('brand_ajax') !!}',
data : {'month' : month },
columns: [
{ data: 'brand_name', name: 'brand_name' , className: 'text-xl-left'},
{ data: 'brand_volume', name: 'brand_volume', className: 'text-xl-right' },
{ data: 'brand_margin', name: 'brand_margin' , className: 'text-xl-right'},
{ data: 'brand_commission', name: 'brand_commission', className: 'text-xl-right' },
]
});
});
</script>
Here is my ajax function to return data
public function brand_ajax()
{
$month = $_POST["month"];
$brands = SaleInvoice::select(DB::raw('brands.name as brand_name,
avg(NULLIF(margin,0)) as brand_margin,
sum(commission) as brand_commission,
sum(amt_invoiced) as brand_volume
'))
->join('brands', 'brands.ext_id', '=', 'saleinvoices.brand_id')
->where('brands.is_active', '=', true)
// ->whereRaw('MONTH(saleinvoices.invoice_date) = ?', (11))
->whereRaw('MONTH(saleinvoices.invoice_date) = ?', ($month))
->having('brand_volume', '>', 0)
->groupBy('brands.name')
->get();
return DataTables::of($brands)
->editColumn('brand_commission', function ($brand) {
return number_format($brand->brand_commission, 2);
})
->editColumn('brand_margin', function ($brand) {
return number_format($brand->brand_margin, 2);
})
->editColumn('brand_volume', function ($brand) {
return number_format($brand->brand_volume, 2);
})
->make(true);
}
I resolved it by myself. I just added the parameter to the URL string.
url('brand_ajax/' . $month)
I am having trouble getting my angular-datatable to show a new column list after a rerender. I have followed the example shown in the docs for rerendering and I can get the table to rerender. I am able to manipulate certain features like searching and pageLength, but for some reason I cannot get my columns to change.
I have a very deep data set that would make my table look awful if I rendered all the columns at once, so I would like to give users the ability to select which columns they see.
I would even be open to loading in all the columns at once and just switching visibility off and on, but I cannot effect visibility either.
Has anyone had this issue before?
Rerender function:
rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
dtInstance.destroy();
// these work
this.dtOptions.searching = true;
this.dtOptions.pageLength = 2;
// these do not
this.dtOptions.columns = newColumnList;
this.dtOptions.columns[some-index].visible = false;
this.dtTrigger.next();
});}
Initial dtOptions:
this.dtOptions = {
searching: false,
pagingType: 'full_numbers',
pageLength: 10,
retrieve: true,
serverSide: true,
processing: true,
language: {
zeroRecords: 'Nothing Found'
},
ajax: (dataTablesParameters: any, callback) => {
const payload = this.passFilterService.processPagination(this.filter, dataTablesParameters);
this.http
.post<any>(
environment.api + '/things/list',
{payload: payload}, {}
).subscribe(resp => {
if (resp.data.data === null) {
resp.data.data = 0;
}
callback({
recordsFiltered: resp.data.totalCount,
data: resp.data.data,
recordsTotal: resp.data.totalCount
});
});
},
columns: this.tableColumns
};
Initial Columns (limited fields):
tableColumns = [
{
title: 'Customer',
data: 'Id',
render: function(data) {
return `Action`;
}
}, {
title: 'Created',
data: 'createdAt',
orderable: true,
visible: true,
}, {
title: 'Updated',
data: 'updatedAt',
orderable: true,
visible: true,
}, {
title: 'Disabled',
data: 'isVoided',
orderable: true,
visible: true,
}
];
Table implementation:
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
</table>
I faced the same issue, spent hours debugging it until I found something that worked for me. I will advice separating the DT config into an independent object that can be loaded separately. Once you update your DT options and any other config, you can use the functions below to reload the entire DT, destroying and reloading it accordingly;
async rerender(newSettings?: DataTables.Settings) {
try {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
if (newSettings) {
// FIX To ensure that the DT doesn't break when we don't get columns
if (newSettings.columns && newSettings.columns.length > 1) {
dtInstance.destroy();
this.dtOptions = Promise.resolve(newSettings);
this.displayTable(this.dtTableElement);
}
}
});
} catch (error) {
console.log(`DT Rerender Exception: ${error}`);
}
return Promise.resolve(null);
}
This function calls the below one to actually destroy the DT and rerender it.
private displayTable(renderIn: ElementRef): void {
this.dtElement.dtInstance = new Promise((resolve, reject) => {
Promise.resolve(this.dtOptions).then(dtOptions => {
// Using setTimeout as a "hack" to be "part" of NgZone
setTimeout(() => {
$(renderIn.nativeElement).empty();
var dt = $(renderIn.nativeElement).DataTable(dtOptions);
// this.dtTrigger.next();
resolve(dt);
});
}).catch(error => reject(error));
});
}
I removed the dtTrigger execution from the reconstruction function as this was executing twice.
The dtTableElement is defined as #ViewChild('dtTableElement') dtTableElement: ElementRef; where the HTML contains the respective reference on the datatable as:
<table #dtTableElement datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped row-border hover" width="100%"></table>
I have this code
dojo.ready(function(){
inventoryStore = new dojo.store.JsonRest({
target: "http://localhost:9080/driver/dojoMVC",
idProperty: "name",
put: function(object, options){
if(object.quantity < 0){
throw new Error("quantity must not be negative");
}
}
});
results = inventoryStore.query("");
var storeData = new dojo.data.ItemFileWriteStore({
data:dojo.fromJson(results)
});
gridLayout = [
{ name: 'Name', field: 'name', editable: true},
{ name: 'Quantity', field: 'quantity'},
{ name: 'Category', field: 'category'}];
var grid = new dojox.grid.DataGrid({
store: storeData,
clientSort: true,
structure: gridLayout
}, dojo.byId("gridElement"));
grid.startup();
When i run it i receive this strange error in FF console
SyntaxError: missing ] after element list
[Break On This Error]
([object Object])
json.js (line 26, col 9)
Can anyone help me with this?
Thanks
maybe you must setup your Layout like this :
var layout = [[
{name:"Id", field: "ident", width:"30%"},
{name:"Name", field: "name", width:"70%"}
]];
In Ev'ry Example i find in dojo the layout is in double brackets.
This would explain why the Error says " missing ]".
Look:
http://dojotoolkit.org/reference-guide/1.9/dojo/data/ItemFileWriteStore.html?highlight=itemfilewritestore#itemfilewritestore-changes-reflected-in-dojox-data-datagrid
Update1
so the Error lies in the store. Have you tried to fill in the data like:
results = inventoryStore.query( name : "*"); // to query all items
Have you checked it there are any results in "results"?
var storeData = new dojo.data.ItemFileWriteStore({
data:results
});
After all i would try to fill in the data without dojo.fromJson.
Give it a try.
Regards, Miriam
The problem is inside the code you posted, which has a syntax error at the very end around line 26. You started with dojo.ready({ but didn't finish it with });
Here, reformatted to make it more obvious:
dojo.ready(function(){
inventoryStore = new dojo.store.JsonRest({
target: "http://localhost:9080/driver/dojoMVC",
idProperty: "name",
put: function(object, options){
if(object.quantity < 0){
throw new Error("quantity must not be negative");
}
}
});
results = inventoryStore.query("");
var storeData = new dojo.data.ItemFileWriteStore({
data:dojo.fromJson(results)
});
gridLayout = [
{ name: 'Name', field: 'name', editable: true},
{ name: 'Quantity', field: 'quantity'},
{ name: 'Category', field: 'category'}
];
var grid = new dojox.grid.DataGrid({
store: storeData,
clientSort: true,
structure: gridLayout
}, dojo.byId("gridElement"));
grid.startup();
Try adding:
});
Also, you're missing some var keywords in there.
need some help for the proper syntax for display the event times in agenda view. The events only shows up under all day despite having allDay set to false.
My json.html page looks like this:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
eventSources: [
{
url: 'json-events.php', // use the `url` property
color: 'yellow', // an option!
textColor: 'black', // an option!
editable: false
},
// Dont forget coma - but not on the last one
{
url: 'other-events.php', // use the `url` property
color: 'red',
textColor: 'black',
editable: 'false',
allDay: 'false'
}
// any other sources...
]
});
});
One of the php pages looks like this:
<?php
echo json_encode(array(
array(
'id' => 112,
'title' => "What is this?",
'start' => "2011-10-11T13:00:00",
'end' => "2011-10-12T15:00:00",
'allDay' => "false"
),
));
?>
How do I get the events to display in the week and day agend view with the proper time (instead of being listed under the "all day" section)?
Thanks,
Extreme Newbie
After tweaking the code, I got it to work by removing the "" around false. The php page should look like this:
'allDay' => false
:)
You need to take the quotation off of "false". "false" is a string, and false is the correct "bool" false.
Also, your json call should have a query such as...
$sql = mysql_query("query") or die(mysql_error());
Followed by a while statement to retrieve the information...
while($arr = mysql_fetch_array($sql)){
$array_content[] = $arr;
}
Then encode...
echo json_encode($array_content);
This will render whatever data you have in the database.
A simple if statement within the while statement will change the string to a bool like so...
if($arr['allDay'] === "true"){
$arr['allDay'] = true;
} else {
$arr['allDay'] = false;
}
}
Hope this helps!