Multiple response loading in XTemplate - json

In my application JSON response doesn't have any root variable ,It comes as following when i call the JSON
[
{
"itemID" : "1",
"errorMsg" : "",
"itemName" : "Car",
"itemDesc" : "Model NEW 2003",
"itemPurchased" : "N",
"itemImage" : "dsafadsf3r3rsdcvcawtr",
"response" : "Success"
},
{
"itemID" : "2",
"errorMsg" : "",
"itemName" : "Bike",
"itemDesc" : "Model NEW 2003",
"itemPurchased" : "N",
"itemImage" : "dsafadsf3r3rsdcvcawtr",
"response" : "Success"
},
{
"itemID" : "3",
"errorMsg" : "",
"itemName" : "Airplane",
"itemDesc" : "Model NEW 2003",
"itemPurchased" : "N",
"itemImage" : "dsafadsf3r3rsdcvcawtr",
"response" : "Success"
}
]
JSON Calling method
function viewgiftlist()
{
Ext.Ajax.request({
// url: App.gvars.apiurl + 'ShowItems/userID='+App.gvars.userid, // url : this.getUrl(),
url : 'http://192.168.1.155:8181/WishList/ShowItems/userID=1',
method: "GET",
useDefaultXhrHeader: false,
withCredentials: true,
success: function (response) {
//alert("Success Alert");
var respObj = Ext.JSON.decode(response.responseText);
// alert(respObj);
Ext.getCmp('myitemspnl').setData(respObj[0]);//Object specfying
Ext.Msg.alert("Success",response);
},
failure: function (response) {
var respObj = Ext.JSON.decode(response.responseText);
// alert("Failure Alert");
Ext.Msg.alert("Error",response.responseText);
}
});
}
JSON Loading Panel
tpl: new Ext.XTemplate(
'<div style="margin:0px;background:#fff;" ><table style="margin:0px;padding:0px;height:40px;" width="100%" ><tr><td style="padding:2px 5px;width:90%;"><span><img src=""/></span><span>{itemName}<br>{itemDesc}</span></td><td style="padding:2px 10px;width:10%;"><img src="resources/img/arrow.png" onclick="viewgiftdetails(\'{itemId}\',\'{itemPurchased}\',this)"/></td></tr></table></div>',
I can show the contents by given the index at respObj[0] or respObj[1]. How to show/load all contents which coming JSON response.Please help to solve

You should try like this
Ext.create('Ext.List', {
width: 320,
height: 290,
id : 'itemList',
itemTpl: ['<div style="margin:0px;background:#fff;" >'+
'<table style="margin:0px;padding:0px;height:40px;" width="100%" >'+
'<tr><td style="padding:2px 5px;width:90%;"><span><img src=""/>'+
'</span><span>{itemName}<br>{itemDesc}</span></td>'+
'<td style="padding:2px 10px;width:10%;">'+
'<img src="resources/img/arrow.png" />'+
'</td></tr></table></div>'].join(),
listeners : {
itemtap: function (list, index, item, record, senchaEvent) {
if (senchaEvent.event.target.nodeName == 'IMG') {
var data = record.getData();
var itemId = data.itemId;
var itemPurchased = data.itemPurchased;
// Call viewgiftdetails method and pass itemId and itemPurchased
}
}
}
});
In ajax request success method set data for the list
success: function (response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.getCmp('itemList').setData(respObj);
Ext.Msg.alert("Success",response);
},

Related

How do I create a Hierarchical Pie chart in html and servlet or jsp?

I want to create a Hierarchical Pie chart that displays percentages? How do I create a Hierarchical Pie chart using d3 in Java?
It should look like this: http://yhnavein.github.io/d3-hierarchical-pie/
Please provide me code to create using jsp, ajax, json and servlet.
if ($('#Start_date').val().length==0 ) {
alert("Please Select Start Date");
}else if($('#end_date').val().length==0){
alert("Please Select End Date");
}
else{
$('#chart-container-OTAType').text();
var graphData;
var data = {
action: "getOTATypeByDate",
fromDate: fromDate,
toDate: toDate
};
var dataString = 'MainJson=' + JSON.stringify(data);
$.ajax({
type: 'POST',
url: './OTAServlet',
data: dataString,
dataType: 'text',
async: false,
success: function (result) {
var responseData = $.trim(result);
graphData = JSON.parse(responseData);
if (FusionCharts('OTAType-Pie-chart')) {
FusionCharts('OTAType-Pie-chart').dispose();
}
$("#divOTATypeGraph").text('');
var chart = new FusionCharts({
type: 'pie2d',
renderAt: 'divOTATypeGraph',
id: 'OTAType-Pie-chart',
width: '650',
height: '500',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Report for OTA",
"showvalues": "1",
"showpercentvalues": "1",
"showpercentintooltip": "0",
"bgcolor": "#FFFFFF",
"basefontcolor": "#400D1B",
"showshadow": "0",
"animation": "0",
"showborder": "0",
"paletteColors": '#9B609B,#AACB47,#1A9494,#BE6F71, #AACB47',
},
"data": graphData
},
"events": {
"dataPlotClick": function (eventObj, dataObj) {
var text = dataObj.categoryLabel;
if(text == 'OTA') {
otaStatus = 1;
}
if (otaStatus > 0) {
getBrandStatusByDate(otaStatus);
}
}
}
});
chart.render();
}

Datatables.js issues and questions

I have a action in my controller that returns a list of activities and this was rendering to my datatable without issue, however, I did not see the number of records displayed at the bottom of the table rendering properly. I did some digging and it looks like there are some additional properties required to get this to work. I added those properties in my controller and ajax call and now I see 'Showing 1 of 3 of 3 entries' but no data in my datatable.
So here is my controller action when the datatable displays results but 'Showing 0 of 0 ...' is displayed.
Controller
[HttpPost]
public JsonResult GetAllActivities(int UserId)
{
return Json(repository.GetAllActivities(UserId), JsonRequestBehavior.AllowGet);
}
HTML
<div class="panel-body">
<table id="master" class="table table-striped table-hover table-condensed" cellspacing="0">
<thead>
<tr>
<th class="rpt_col_bg_head" style="width: 3%;"></th>
<th class="rpt_col_bg_head" style="width: 20%;">Result</th>
<th class="rpt_col_bg_detail" style="width: 20%;">Work Activity</th>
<th class="rpt_col_bg_detail" style="width: 180px;">Effort(%)</th>
<th class="rpt_col_bg_detail" style="width: 7%;">Status</th>
<th class="rpt_col_bg_detail" style="width: 30%;">Were there any innovations</th>
<th class="rpt_col_bg_detail text-center" style="width: 7%;">Action</th>
</tr>
</thead>
</table>
</div>
JavaScript
var table = $('#master').DataTable( {
"processing": true,
"serverSide": true,
"columnDefs" : [{
"targets" : [0],
"visible" : true,
"searchable" : false
}],
"ajax" : {
"type" : "POST",
"url" : "#Url.Action("GetAllActivities", "Activities")",
"data" : { "UserId" : employeeId },
"dataSrc" : ""
},
"columns": [
{
"className" : "details-control", "orderable" : false, "data": "ActivityHistoryId" },
{ "data" : "ParentName" },
{ "data" : "ActivityName" },
{ "data" : "Effort" },
{ "data" : "Status" },
{ "data" : "Innovation" },
{ "defaultContent" : '<td><div><button class="btn btn-xs btn-primary" title="edit work activity" name="editWork"></button></div></td>' }]
});
According to the documentation below some additional properties are required to get the footer to work.
https://datatables.net/manual/server-side
I modified my controller action and html accordingly.....
[HttpPost]
public JsonResult GetAllActivities(int UserId)
{
int count = 0;
var data = repository.GetAllActivities(UserId);
foreach (var item in results)
{
count++;
}
return Json(new { draw = 1, recordsTotal = count, recordsFiltered = count, data }, JsonRequestBehavior.AllowGet);
}
HTML
var table = $('#master').DataTable({
"processing": true,
"serverSide": true,
"columnDefs" : [{
"targets" : [0],
"visible" : true,
"searchable" : false
}],
"ajax" : {
"type" : "POST",
"url" : "#Url.Action("GetAllActivities", "Activities")",
"data" : { "UserId" : employeeId },
"dataFilter" : function(data) {
var json = jQuery.parseJSON(data);
json.recordsTotal = json.recordsTotal;
json.recordsFiltered = json.recordsFiltered;
json.data = json.data;
return JSON.stringify(json);
},
"dataSrc" : ""
},
"columns": [
{ "className" : "details-control", "orderable" : false, "data": "ActivityHistoryId" },
{ "data" : "ParentName" },
{ "data" : "ActivityName" },
{ "data" : "Effort" },
{ "data" : "Status" },
{ "data" : "Innovation" },
{ "defaultContent" : '<td><button class="btn btn-xs btn-primary" title="edit work activity" name="editWork"></button></div></td>' }]
});
Here is the JSON returned from my controller, which is valid.
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"ActivityHistoryId":1,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 1","ActivityDescription":"Description of Test Activity 1","Status":"\u003cspan class=\u0027badge badge-blue\u0027\u003eNot Started\u003c/span\u003e","Effort":10,"Innovation":false,"ParentId":2,"ParentName":"Test Result 1"},{"ActivityHistoryId":2,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 2","ActivityDescription":"Description of Test Activity 2","Status":"\u003cspan class=\u0027badge badge-blue\u0027\u003eNot Started\u003c/span\u003e","Effort":16,"Innovation":false,"ParentId":2,"ParentName":"Test Result 1"},{"ActivityHistoryId":3,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 3","ActivityDescription":"Description of Test Activity 3","Status":"\u003cspan class=\u0027badge badge-lightBlue\u0027\u003eIn Progress\u003c/span\u003e","Effort":25,"Innovation":false,"ParentId":5,"ParentName":"Test Result 2"}]}
And the datatable...
Any idea how to get BOTH the datatable to render data AND show the number of entries in the table? I find the documentation does not work for every scenario I try.
I used the following to see the data returned...
table.on('xhr', function () {
var json = table.ajax.json();
console.log(table.ajax.json());
});
If you remove dataSrc things should start working:
var table = $('#master').DataTable({
"processing": true,
"serverSide": true,
"columnDefs": [{
"targets": [0],
"visible": true,
"searchable": false
}],
"ajax": {
"type": "POST",
"url": "#Url.Action("
GetAllActivities ", "
Activities ")",
"data": {
"UserId": employeeId
},
"dataFilter": function(data) {
var json = jQuery.parseJSON(data);
json.recordsTotal = json.recordsTotal;
json.recordsFiltered = json.recordsFiltered;
json.data = json.data;
return JSON.stringify(json);
}
},
"columns": [{
"className": "details-control",
"orderable": false,
"data": "ActivityHistoryId"
}, {
"data": "ParentName"
}, {
"data": "ActivityName"
}, {
"data": "Effort"
}, {
"data": "Status"
}, {
"data": "Innovation"
}, {
"defaultContent": '<td><button class="btn btn-xs btn-primary" title="edit work activity" name="editWork"></button></div></td>'
}]
});
Glad that helped. :-)
I don't see problem with the data or server side code - it is the way you are assigning data.
I just assigned data without AJAX and it works see the fiddle https://jsfiddle.net/jituce/1naw041z/6/
var table = $('#master').DataTable( {
"processing": true,
"data":[{"ActivityHistoryId":1,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 1","ActivityDescription":"Description of Test Activity 1","Status":"\u003cspan class=\u0027badge badge-blue\u0027\u003eNot Started\u003c/span\u003e","Effort":10,"Innovation":false,"ParentId":2,"ParentName":"Test Result 1"},{"ActivityHistoryId":2,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 2","ActivityDescription":"Description of Test Activity 2","Status":"\u003cspan class=\u0027badge badge-blue\u0027\u003eNot Started\u003c/span\u003e","Effort":16,"Innovation":false,"ParentId":2,"ParentName":"Test Result 1"},{"ActivityHistoryId":3,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 3","ActivityDescription":"Description of Test Activity 3","Status":"\u003cspan class=\u0027badge badge-lightBlue\u0027\u003eIn Progress\u003c/span\u003e","Effort":25,"Innovation":false,"ParentId":5,"ParentName":"Test Result 2"}],
"serverSide": false,
"columnDefs" : [{
"targets" : [0],
"visible" : true,
"searchable" : false
}],
"columns": [
{
"className" : "details-control", "orderable" : false, "data": "ActivityHistoryId" },
{ "data" : "ParentName" },
{ "data" : "ActivityName" },
{ "data" : "Effort" },
{ "data" : "Status" },
{ "data" : "Innovation" },
{ "defaultContent" : '<td><div><button class="btn btn-xs btn-primary" title="edit work activity" name="editWork"></button></div></td>' }]});
I would say remove JSON.stringy or dataFilter from the AJAX and it should work fine.
Let me know if this helps.

Angular.js table mapping brain fahrt

I'm new to front end development and am playing with angular.js (1.4.8). In the code below, I do an http get. I then
map the json data into a table. I think I have a mapping problem, ie, the ng-repeat isn't pulling stuff out of the
json correctly. Or perhaps it's something else and I'm unintentionally misleading you. Do you see a programming
error here?
Here is the relevant html:
<div class="table-responsive" data-ng-app="myApp" data-ng-controller="customersCtrl">
<table class="table table-striped">
<thead>
<tr>
<th data-ng-repeat="header in headers">{{header}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="record in records track by $index">
<td>{{ record.data.day }}</td>
<td>{{ record.data.date }}</td>
<td>{{ record.data.value }}</td>
</tr>
</tbody>
</table>
</div>
Here is my angular file:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
$scope.init = function () {
$http.get("https://localhost:4567/1")
.then(function (response) {
var json = angular.toJson(response.data.records);
$scope.records = json;
$scope.headers = response.data.headers;
});
};
$scope.httpPost = function (journal) {
var theJson = angular.toJson(journal);
var successCallback = function (data, status, headers, config) {
$scope.postResponse = data;
};
var errorCallback = function (data, status, headers, config) {
console.log();
};
$http.post('https://localhost:4567/journal', {"foo": "bar"}).then(successCallback, errorCallback);
};
$scope.master = {};
$scope.update = function (journal) {
$scope.master = angular.copy(journal);
};
$scope.reset = function () {
$scope.journal = angular.copy($scope.master);
};
$scope.init();
$scope.reset();
});
Here is the response body (json):
{
"headers" : [ "day", "date", "value" ],
"records" : [ {
"data" : {
"day" : "Tuesday",
"date" : "5/3/2011",
"value" : "2.6"
},
"id" : "646312cc-1931-4137-af2a-e712300b489b",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "3bee5500-fd03-4d69-84af-8b8dc85292b0"
}, {
"data" : {
"day" : "Wednesday",
"date" : "5/4/2011",
"value" : "2.6"
},
"id" : "f58eae54-6b30-4f61-b8cc-b04984a8436a",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "29e4dc69-c118-4fad-91ae-8a1efaf9b984"
}, {
"data" : {
"day" : "Thursday",
"date" : "5/5/2011",
"value" : "2.6"
},
"id" : "ebf8dba4-52a9-4e0b-a575-cda2ea29a2ea",
"dateCreated" : 1453842720871,
"dateUpdated" : 1453842720871,
"etag" : "986961bb-84ff-4ac6-9f70-96827006ed87"
} ],
"id" : null,
"dateCreated" : null,
"dateUpdated" : null,
"etag" : null
}
=====
As pointed out by two people, the problem was this line (I had turned json object to debug something and forgot to revert ;(
var json = angular.toJson(response.data.records);
Angular's $httpProvider automatically adds the Content-Type: application/json header to all outgoing service requests made by your application.
In addition, it will also automatically deserialise responses using a JSON parser if a JSON-like response is detected.
As such, there is no need to use functions like angular.toJson() to do the JSON conversion yourself unless you have overridden the default provider behaviour somewhere.
Glad that helped. :-)

How to display nested JSON in sap.m Table (SAPUI5) for each listItem

I have a sap.m splitApp where i have an overview of courses. By displaying a course you get detail information like the list of participants for that course. Currently it is only possible to display the participants of the same (one) course for all courses. How can i display the appropriate participants for each course.
If anyone has an idea that would be great :) Thanks.
This is my "Details.view"
sap.ui.jsview("tem_trainer.Details", {
/** Specifies the Controller belonging to this View.
* In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
* #memberOf tem_trainer.Details
*/
getControllerName : function() {
return "tem_trainer.Details";
},
onBeforeFirstShow: function(oEvent){
this.getController().onBeforeFirstShow(oEvent);
},
/** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.
* Since the Controller is given to this method, its event handlers can be attached right away.
* #memberOf tem_trainer.Details
*/
createContent : function(oController) {
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
var utc1 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
var utc2 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
return Math.floor((utc2 - utc1) / (1000 * 60 * 60 * 24));
}
var oTimestamp = new sap.m.ObjectAttribute({
text: '{start} - {end}, {starttime} - {endtime}',
});
var oRoom = new sap.m.ObjectAttribute({
text: "{room}",
});
var oHeader = new sap.m.ObjectHeader({
title: "{name}",
number: "{start}",
numberUnit: "Start Date",
attributes: [
oTimestamp, oRoom
]
});
var oTable = new sap.m.Table("idRandomDataTable", {
headerToolbar : new sap.m.Toolbar({
content : [ new sap.m.Label({
text : "Participant List"
}), new sap.m.ToolbarSpacer({}), new sap.m.Button("idPersonalizationButton", {
icon : "sap-icon://person-placeholder"
}) ]
}),
columns : [
new sap.m.Column({
width : "2em",
header : new sap.m.Label({
text : "Firstname"
})
}),
new sap.m.Column({
width : "2em",
header : new sap.m.Label({
text : "Lastname"
})
}),
new sap.m.Column({
width : "2em",
header : new sap.m.Label({
text : "Job"
})
}),
new sap.m.Column({
width : "2em",
header : new sap.m.Label({
text : "Company"
})
})
]
});
var oModel1 = new sap.ui.model.json.JSONModel();
var model = sap.ui.getCore().getModel();
var aData = model.getProperty("/courses");
oModel1.setData({
modelData : aData
});
oTable.setModel(oModel1);
oTable.bindItems("/modelData/0/participant", new sap.m.ColumnListItem({
cells : [ new sap.m.Text({
text : "{firstname}"
}), new sap.m.Text({
text : "{lastname}"
}), new sap.m.Text({
text : "{job}",
}), new sap.m.Text({
text : "{company}",
}),]
}));
var oIconTabBar = new sap.m.IconTabBar({
items: [
new sap.m.IconTabFilter({
text: "General",
icon: "sap-icon://hint",
content: [
]
}),
new sap.m.IconTabFilter({
text: "Participants",
icon: "sap-icon://visits",
content: [
oTable
]
}),
]
});
return this.page = new sap.m.Page({
title: "Course Details",
content: [
oHeader, oIconTabBar
]
});
}
});
This is my "Details.controller"
sap.ui.controller("tem_trainer.Details", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* #memberOf tem_trainer.Details
*/
// onInit: function() {
//
// },
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* #memberOf tem_trainer.Details
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* #memberOf tem_trainer.Details
*/
// onAfterRendering: function() {
//
// },
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* #memberOf tem_trainer.Details
*/
// onExit: function() {
//
// }
onBeforeFirstShow: function(oEvent){
if(oEvent.data.bindingContext){
// Binding Kontext setzen
this.getView().page.setBindingContext(oEvent.data.bindingContext);
}
},
onListSelect: function(oEvent){
var oBindingContext = oEvent.getParameter(
"listItem").getBindingContext();
var sViewId = "detailCourse_" +
oEvent.getParameter(
"listItem").data("req_id");
sap.ui.getCore().getEventBus().publish(
"nav",
"to", {
viewName: "tem_trainer.Details",
viewId: sViewId,
data: {
bindingContext: oBindingContext
}
});
},
onListItemTap: function(oEvent){
var oBindingContext = oEvent.oSource.getBindingContext();
var sViewId = "detailCourse_" +
oEvent.oSource.data("req_id");
sap.ui.getCore().getEventBus().publish(
"nav",
"to", {
viewName: "tem_trainer.Details",
viewId: sViewId,
data: {
bindingContext: oBindingContext
}
});
},
onNavButtonTap: function(){
// Wird ausgeführt wenn die Hardwaretaste
// oder der Back-Button gedrückt wird
sap.ui.getCore().getEventBus().publish(
"nav", "back");
}
});
This is my "Courses.json"
{
"courses": [
{
"req_id": "1",
"name" : "ABAP OO Basics",
"start" : "20-08-2014",
"end" : "22-08-2014",
"starttime": "10:00:00",
"endtime": "16:00:00",
"status": "Booked",
"room": "Room CDE",
"adress" : "Adress No.1",
"street": "Street No.1",
"zip_code": "74892142578485",
"city": "City No.1",
"country": "Country No.1",
"phone": "0595726764675435497436497",
"fax":"12",
"cap_min": "10",
"cap_opt": "20",
"cap_max": "30",
"img": "./res/1.jpg",
"content": "Test",
"participant": [{ "firstname": "Maik",
"lastname": "Maier",
"job": "installer",
"company": "muster"
},
{ "firstname": "Marco",
"lastname": "Schmidt",
"job": "installer",
"company": "schmitt"
},
{ "firstname": "Hans",
"lastname": "Mueller",
"job": "installer",
"company": "muster"
},
{ "firstname": "Matthias",
"lastname": "Gottlieb",
"job": "installer",
"company": "schmitt"
}]
},
{
"req_id": "2",
"name" : "ABAP OO Basics II",
"start" : "22-08-2014",
"end" : "23-08-2014",
"starttime": "11:00:00",
"endtime": "14:00:00",
"status": "Booked",
"room": "Room XYZ",
"adress" : "Adress No.2",
"street": "Street No.2",
"zip_code": "2222",
"city": "City No.2",
"country": "Country No.2",
"phone": "22222",
"fax":"2222",
"cap_min": "10",
"cap_opt": "20",
"cap_max": "30",
"img": "./res/2.jpg",
"content": "Test",
"participant": [{ "firstname": "Name",
"lastname": "Name",
"job": "installer",
"company": "muster"
},
{ "firstname": "Name2",
"lastname": "Name2",
"job": "installer",
"company": "schmitt"
}]
}
]
}
EDIT: Here is my "Master.controller"
sap.ui.controller("tem_trainer.Master", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* #memberOf tem_trainer.Master
*/
// onInit: function() {
//
// },
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* #memberOf tem_trainer.Master
*/
onBeforeRendering: function() {
var oInbox = sap.ui.getCore().byId("inboxList");
oInbox.removeSelections();
var oJSONDataModel = new sap.ui.model.json.JSONModel();
oJSONDataModel.loadData("./json/Courses.json");
sap.ui.getCore().setModel(oJSONDataModel);
},
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* #memberOf tem_trainer.Master
*/
// onAfterRendering: function() {
//
// },
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* #memberOf tem_trainer.Master
*/
// onExit: function() {
//
// }
onBeforeFirstShow: function(oEvent) {
this.bindListData();
if(oEvent.data.title) {
this.getView().page.setTitle(oEvent.data.title);
}
},
bindListData: function(aFilters){
var that = this;
this.getView().oList.bindAggregation("items", {
path: "/courses",
factory: function(sId){
return new sap.m.StandardListItem(sId, {
icon : "sap-icon://course-program",
title: {
path:"name",
},
description: {
path:"start",
},
type: jQuery.device.is.phone?
sap.m.ListType.Navigation : sap.m.ListType.None,
customData: [
new sap.ui.core.CustomData({
key: "req_id",
value: "{req_id}"
}),
],
tap: [that.onListItemTap, that]
}).setInfoState(sap.ui.core.ValueState.Success);
},
filters: aFilters
});
},
onListSelect: function(oEvent){
var oBindingContext =
oEvent.getParameter(
"listItem"
).getBindingContext(),
sViewId = "detailCourse_" +
oEvent.getParameter(
"listItem").data("req_id");
// Ereignis an EventBus übergeben
sap.ui.getCore().getEventBus().publish(
"nav",
"to", {
viewName: "tem_trainer.Details",
viewId: sViewId,
data: {
bindingContext: oBindingContext
}
});
},
onListItemTap: function(oEvent){
// siehe onListSelect
var oBindingContext =
oEvent.oSource.getBindingContext(),
sViewId = "detailCourse_" +
oEvent.oSource.data("req_id");
sap.ui.getCore().getEventBus().publish(
"nav",
"to", {
viewName: "tem_trainer.Details",
viewId: sViewId,
data: {
bindingContext: oBindingContext
}
});
},
//Navigation Zurück
onNavButtonTap: function(){
sap.ui.getCore().getEventBus().publish(
"nav",
"back"
);
},
//Search Functionality
handleSearch: function(oEvent) {
this._updateList();
},
_updateList : function () {
var filters = [];
//var oView = this.getView();
// Filter für die Suche
//var searchString = oView.byId("searchField").getValue();
var searchString = sap.ui.getCore().byId("searchField").getValue();
if (searchString && searchString.length > 0) {
var filter = new sap.ui.model.Filter("name", sap.ui.model.FilterOperator.Contains, searchString);
filters.push(filter);
}
// List Binding updaten
//var list = oView.byId("inboxList");
var list = sap.ui.getCore().byId("inboxList");
var binding = list.getBinding("items");
binding.filter(filters);
},
});
EDIT: This is what i adjusted:
Details.controller
onInit : function() {
var bus = sap.ui.getCore().getEventBus();
bus.subscribe("nav", "to", this.navToHandler, this);
},
navToHandler : function(channelId, eventId, data) {
if (data && data.viewId) {
var oBindingContext = data.data.bindingContext;
this.getView().setBindingContext(oBindingContext);
}
},
//This is a function i already had and which is called by the view
onBeforeFirstShow: function(oEvent){
if(oEvent.data.bindingContext){
// Binding Kontext setzen
this.getView().page.setBindingContext(oEvent.data.bindingContext);
}
},
In my Details.view
var oModel1 = new sap.ui.model.json.JSONModel();
var model = sap.ui.getCore().getModel();
var aData = model.getProperty("/courses");
oModel1.setData({
modelData : aData
});
oTable.setModel(oModel1);
oTable.bindItems("participant", new sap.m.ColumnListItem({
cells : [ new sap.m.Text({
text : "{firstname}"
}), new sap.m.Text({
text : "{lastname}"
}), new sap.m.Text({
text : "{job}",
}), new sap.m.Text({
text : "{company}",
}),]
}));
Your requirement is similar to the demo app of Approve Purchase Orders.
See the json string:
https://openui5.hana.ondemand.com/test/resources/sap/m/demokit/poa/model/mock.json
Courses 1 : n Course 1 : n Participants
PurchaseOrderCollection 1 : n PurchaseOrder 1 :n PurchaseOrder_Items
You already did publish eventbus in your master controller when use selects the list item in the master view:
onListSelect: function(oEvent){
var oBindingContext =
oEvent.getParameter(
"listItem"
).getBindingContext(),
sViewId = "detailCourse_" +
oEvent.getParameter(
"listItem").data("req_id");
// Ereignis an EventBus übergeben
sap.ui.getCore().getEventBus().publish(
"nav",
"to", {
viewName: "tem_trainer.Details",
viewId: sViewId,
data: {
bindingContext: oBindingContext
}
});
},
You need to subscribe the eventbus in your Detail view controller to get the Binding Context of your list item and set the binding context for your detail view, in your case the single course.
onInit : function() {
var bus = sap.ui.getCore().getEventBus();
bus.subscribe("nav", "to", this.navToHandler, this);
},
navToHandler : function(channelId, eventId, data) {
if (data && data.viewId) {
var oBindingContext = data.data.bindingContext;
this.getView().setBindingContext(oBindingContext);
}
},
And adjust your binding paths of the table in the detail view, do not hard code 0.
oTable.bindItems("participant", new sap.m.ColumnListItem({
cells : [ new sap.m.Text({
text : "{firstname}"
}), new sap.m.Text({
text : "{lastname}"
}), new sap.m.Text({
text : "{job}",
}), new sap.m.Text({
text : "{company}",
}),]
}));

Backbone underscore where inside json

I have an app in backbone where I want to find inside a Json record where hotel_id = 1 for example.
I have done in this mode:
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model:Room,
url : "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function(){
this.render();
},
render: function(){
this.bindRoomToHotel();
var element = this.$el;
element.html('');
// $(this.el).html(this.template({hotels: this.collection.models}));
},
bindRoomToHotel: function() {
allRooms = new Rooms();
allRooms.fetch();
rooms = allRooms.where({'hotel_id' : 1});
console.log(rooms);
}
});
I have cut many parts but the problem is inside bindRoomHotel when I make the where function return me empty.
This is my json:
[
{
"id" : "r1",
"hotel_id" : "1",
"name" : "Singola"
},
{
"id" : "r1_1",
"hotel_id" : "1",
"name" : "Doppia"
},
{
"id" : "r2",
"hotel_id" : "2",
"name" : "Singola"
},
{
"id" : "r2_1",
"hotel_id" : "2",
"name" : "Tripla"
}
]
How to find record with hotel_id=1?
Pretty sure you don't need quotes round the attribute name, maybe try this
rooms = allRooms.where({ hotel_id : 1 });
edit: I don't see where you are initializing those objects in the code you have provided, i'd expect to see something like this.
var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
model: Room,
url: "includes/rooms.json"
});
var RoomView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function () {
this.render();
},
render: function () {
this.$el.html(_.template(this.template, this.collection.where({ hotel_id: 1 }));
}
});
var roomsCollection = new Rooms();
var roomView;
roomsCollection.fetch({
success: function ( rooms ) {
roomView = new RoomView( collection: rooms );
}
});