creating dynamic table with data from odata service in ui5 - odata

I'm a complete newb on sap ui5.
I'm trying to generating a table on my webpage generated in sap web ide.
The data for this table is a .json file accessed via odata service.
I've come this far:
oModel is generated:
function initModel() {
var sUrl = "/sap/opu/odata/sap/ZGWS_someService/CollectionSet?$format=json";
var oModel = new sap.ui.model.odata.ODataModel(sUrl, true);
sap.ui.getCore().setModel(oModel);
}
now I want to generate a table on my html site with the data in the .json file.
So I have to create columns based on the properties of the items and then filling the rows with the current data.
.json looks like this:
{
"d": {
"results": [
{
"property1": "123",
"property2": "346"
},
{
"property1": "123",
"property2": "555"
}
I have no solution for this yet - can you help me out?
greetz,
simon

I created the table in the controller and sorted the data via lodash.
Is that good practice?
var oTable = this.byId("table");
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Info1"
}),
sortProperty: "INTST",
template: new sap.ui.commons.TextView().bindProperty("text", "key")
}));
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({
text: "Count"
}),
template: new sap.ui.commons.TextView().bindProperty("text", "value")
}));
$
.ajax({
url: '/.../ServiceSet',
jsonpCallback: 'getJSON',
contentType: "application/json",
dataType: 'json',
success: function(data, textStatus, jqXHR) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
sap.ui.getCore().setModel(oModel);
//Create a model and bind the table rows to this model
//Get the forecastday array table from txt_forecast object
var aData = oModel.getProperty("/d/results");
var aData2 = _.countBy(_.map(aData, function(d) {
return d.VALUE;
}));
var aData3 = Object.keys(aData2).sort().map(key => ({
key,
value: aData2[key]
}));
oModel.setData({
modelData: aData3
});
oTable.setModel(oModel);
}
});
oTable.bindAggregation("rows", {
path: "/modelData"
});

Related

UI5 OData Search Help not displaying values

this is the odata response i am getting:
my desired result would be a search help that displays the "TypRolle", "RolleNr" and "RolleOri" columns of the odata response. But right now i am stuck at trying to just display one of them, the "TypRolle" one.
this is what my search help looks like right now:
As you can see, no values are being displayed.
Here is my valueHelpRequest method:
var roletypeUrl = "my odata url";
var attModel = new sap.ui.model.json.JSONModel();
var link = this.getView().byId("roletype"); // roletype input field
var oDataModel = new sap.ui.model.odata.v2.ODataModel(roletypeUrl, {
json: true,
loadMetadataAsync: true
});
oDataModel.read("/ZshNsiAgr01xxlEinzelTypSet", {
success: function(oData, response) {
attModel.setData(oData);
var oValueHelpDialog = new sap.m.Popover({
title: "Rollentyp auswählen",
footer: [new sap.m.Button({
text: "Ok"
})]
});
oValueHelpDialog.openBy(link);
var oItemTemplate = new sap.m.StandardListItem({
title: "test",
description: "{TypRolle}"
});
var oHelpTable = new sap.m.Table({
width: "300pt",
columns: [
new sap.m.Column({
header: [
new sap.m.Label({
text: "Rollentyp"
})
]
})
],
items: {
path: "/results",
template: oItemTemplate
},
items: [
new sap.m.ColumnListItem({
cells: [
new sap.m.Text({
text: "{TypRolle}"
})
]
})
]
})
oHelpTable.setModel(attModel);
oValueHelpDialog.addContent(oHelpTable);
I am very thankful for any kind of suggestion and look forward to your answers :)
If you have to do it with JSON model ... here it is
]
})
]
})
oHelpTable.bindAggregation("items", "/results", new sap.m.ColumnListItem({
cells: [
new sap.m.Text({
text: "{TypRolle}"
})
]
}));
oHelpTable.setModel(attModel);
oValueHelpDialog.addContent(oHelpTable);
Or else you can directly bind to your default OData model as well and it can fetch the data automatically without you writing the read

How to view a single entry with oModel.read in UI5 Application

I want to display a single entry with oModel.read in my UI5 application and store it in a variable.
What i want to do is, to select a single entry of my Model and store it in a variable:
If i execute my code i get the following in the Browser-Console:
https://ibb.co/FmPNSPm
Here is my code (but is not working):
var hostPort = "";
var oDataPath = "/.../KOMMI_SERVICE/";
var sServiceUrl= hostPort + oDataPath;
var oModel = new sap.ui.model.odata.ODataModel (sServiceUrl, true);
var oJsonModel = new sap.ui.model.json.JSONModel();
var text123;
oModel.read("/Komm(ZSMATERIALTEXT ='"+text123+")",oEntry,null,false,
function(oData, oResponse){
},function(err){
console.log("err");
});
I think that this path "/Komm(ZSMATERIALTEXT ='"+text123+")" is not correct.
You can try using filter. For example:
var sPath = "/Komm";
var oFilter = [
new Filter("ZSMATERIALTEXT", "EQ", text123)
];
oModel.read(sPath, {
filters: oFilter,
success: function (oData, oResponse) {
// save variable
},
error: function (oError) {
// show error
}
});
Try this:
I think you're missing a " ' "...
oModel.read("/Komm(ZSMATERIALTEXT ='"+text123+"')",oEntry,null,false,
function(oData, oResponse){
},function(err){
console.log("err");
});
Or
oModel.read("/Komm", {
filters: [
new sap.ui.model.Filter("ZSMATERIALTEXT", sap.ui.model.FilterOperator.EQ, text123)
],
success: function (oData, oResponse) {
// do some...
},
error: function (oError) {
// error
}
});

Knockout-Kendo dropdownlist Ajax observableArray get selected item name

My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.

Update Kendo Grid based On Search Form Post

I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.
Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());

Backbone.js - How to save model by form and post to server

I'm n00b in BackboneJS/RequireJS and I'm developing an web app that use a RESTful API.
So I've a model like this:
models/pet.js
define([
'backbone'
], function(Backbone){
var PetModel = Backbone.Model.extend({
urlRoot: 'http://localhost:3000/pet',
idAttribute: '_id',
defaults: {
petId: "",
type: "",
name: "",
picture: "",
description: "",
breed: "",
size: "",
sex: "",
age: "",
adopted: false,
}
});
return PetModel;
});
a collection: collections/pets.js
define([
'backbone',
'models/pet'
], function(Backbone, PetModel){
var PetsCollection = Backbone.Collection.extend({
url: 'http://localhost:3000/pets',
model: PetModel,
});
return PetsCollection;
});
And a view that renders a form to add new models (Maybe it's possible another way more elegant)
views/petAddNew.js
define([
'jquery',
'backbone',
'models/pet',
'collections/pets',
'text!templates/pet/addNew.html'
], function($, Backbone, PetModel, PetsCollection, petAddNewTemplate){
var PetAddNewView = Backbone.View.extend({
el: $('#formAdd'),
template: _.template(petAddNewTemplate),
events: {
'click #add' : 'submitAdd',
},
initialize: function() {
this.model = new PetModel();
this.collection = new PetsCollection();
_.bindAll(this, 'submitAdd');
},
render: function() {
var view = this;
view.$el.html( view.template );
return view;
},
submitAdd: function(e) {
//Save Animal model to server data
e.preventDefault();
var pet_data = JSON.stringify( this.getFormData( this.$el.find('form') ) );
this.model.save(pet_data);
this.collection.add(this.model);
return false
},
//Auxiliar function
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
},
});
return PetAddNewView;
});
So when I submit the form I don't post any data to server. I don't know how to fix it.
Any ideas? Thanks in advance!
You need set the attributes first and then save.
//Auxiliar function
getFormData: function(form) {
var self = this;
var unindexed_array = form.serializeArray();
$.map(unindexed_array, function(n, i){
self.model.set({
n['name']: n['value']
});
});
}
Now this.model.save() works (saving on the server side).
You can see it work in a fiddle.
Model.save expect an object/hash of new values, just like Model.set. Here you're passing a string as the attributes arguments.

Resources