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

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
}
});

Related

creating dynamic table with data from odata service in ui5

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"
});

Odata table not showing odata records

I can store odata records but this records not display on my ui table.
App.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast",
"opensap/myapp/model/formatter",
"opensap/myapp/controller/BaseController",
"sap/ui/Device"
], function(Controller, MessageToast, formatter, BaseController, Device) {
"use strict";
return BaseController.extend("opensap.myapp.controller.App", {
formatter: formatter,
onInit: function() {
// View in temasinin ayarlanmasi
var oView = this.getView();
var oComp = this.getOwnerComponent();
oView.addStyleClass(oComp.getContentDensityClass());
this.getRouter().attachRoutePatternMatched(this._onRouteMatched, this);
//View in modelinin ayarlanamsı
var oViewModel = this.getOwnerComponent().getModel();
this.getView().setModel(oViewModel);
},
_onRouteMatched: function(oEvent) {
var oController = this;
var sRouteName = oEvent.getParameter("name");
var oDataModel = this.getView().getModel();
this._getAllMasrafs();
this._getAllMasrafTips();
},
_getAllMasrafs: function(oEvent) {
var oController = this;
var oDataModel = this.getView().getModel();
oDataModel.read("/GetMasrafSet", {
success: function(resp) {
var oMainModel = oController.getView().getModel("mainModel");
if (resp.results.length > 0) {
oMainModel.setProperty('/MasrafId', resp.results[0].MasrafId);
oMainModel.setProperty('/Tarih', resp.results[0].Tarih);
oMainModel.setProperty('/ProjeTanımı', resp.results[0].ProjeTanımı);
oMainModel.setProperty('/FişNumarası', resp.results[0].FişNumarası);
oMainModel.setProperty('/MasrafTipi', resp.results[0].MasrafTipi);
oMainModel.setProperty('/Tutar', resp.results[0].Tutar);
oMainModel.setProperty('/Para', resp.results[0].Para);
oMainModel.setProperty('/Kilometre', resp.results[0].Kilometre);
oMainModel.setProperty('/Lokasyon', resp.results[0].Lokasyon);
oMainModel.setProperty('/Açıklama', resp.results[0].Açıklama);
}
},
error: function(err) {
}
});
},
_getAllMasrafTips: function(oEvent) {
var oController = this;
var oDataModel = this.getView().getModel();
var oViewModel = this.getOwnerComponent().getModel("app");
oDataModel.read("/GetMasrafTipiSet", {
success: function(resp) {
var oMainModel = oViewModel.getData();
/* oMainModel.setProperty("/TAX", resp.results[0].TAX);
oMainModel.setProperty("/Taksi", resp.results[0].Taksi); */
oMainModel.Masraflar=resp.results;
oViewModel.setData(oMainModel);
},
error: function(err) {
}
});
},
getRouter: function() {
var oComponent = this.getOwnerComponent();
return oComponent.getRouter();
},
});
when i press F12 option and debugging, i can see my arrays store in oMainModel but i can not show the records please help me
Where is my mistake?
Thanks
Cansu Koca
There has to be no "/" in your Table "items" binding:
<Panel headerText="Masraf Listesi" expandable="true" expanded="false" >
<content>
<Button press="_onMasrafListesi" text="Click here to see all Masrafs"/>
<Table id="idMasrafTable" items="{Masraf>Masraflar}" visibleRowCountMode="Auto">

How to save data into smart table in UI5?

I have a smart table which has editable fields, I want to save these multiple records in the backend. How should I achieve this?
oModel.create("/Set", [{obj1}, {obj2}])
oModel.createBatchOperation("/set", "POST" , obj1)
oModel.createKey("set" , obj)
oModel.submitChanges()
All of them
use batch call, giving
same error -- 400 -- XML parse error.
If you are using sap.ui.model.odata.v2.ODataModel use below code
var oModel = this.getView().getModel();//gets the v2 odata model
oModel.setUseBatch(true);//setting batch true if not already set
var jModel = oTable.getModel("jTabModel").getProperty("/Carriers");
for (var i = 0; i < jModel.length; i++) {
var oEntry = jModel[i];
oModel.create("/FlightSet", oEntry, {
method: "POST",
success: function(data) {
},
error: function(e) {
}
});
}
oModel.submitChanges({
success: function(data, response) {
//To do
},
error: function(e) {
//To do
}
});

Difficulty with upload csv to knockout js table (ASP MVC)

I've been working with these two tutorials, but am having difficulty merging them together to get an upload csv to populate the table. It most likely is my lack of understanding of the view model.
Here's the tutorial for the knockout js editable table from the knockout js site: KnockoutJS: Editable Grid Table
And here's the tutorial for uploading a csv I'm referencing:
KnockoutJS - Upload CSV
Here's the javascript code I've been working on to upload a csv to my table. I keep getting "JavaScript runtime error: Unable to get property 'push' of undefined or null reference" - I marked in comments the problem spot. As you can see, I'm having trouble with the view model.
<script>
var UserModel = function (users) {
var self = this;
self.users = ko.observableArray(users);
self.addUser = function () {
self.users.push({
id: "",
firstName: "",
lastName: ""
});
};
self.removeUser = function (user) {
self.users.remove(user);
};
self.save = function (form) {
sendData = ko.toJSON(self.users);
$.ajax({
url: '/Users/CreateMultiple',
contentType: 'application/json',
async: true,
type: 'POST',
dataType: 'json',
data: sendData,
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS");
}
});
};
};
var viewModel = new UserModel([
{ id: "", firstName: "", lastName: "" }
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
/////
/////Upload CSV
/////
$('#lnkUpload').click(function () {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
reader.onload = Load_CSVData;
reader.readAsText(FileToRead.files.item(0));
}
});
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
UserModel.users.push(new UserModel()//here's my problem
.id(csvID)
.firstName(csvFirstName)
.lastName(csvLastName)
)
});
}
</script>
I was able to identify the fully qualified for the observable array which in turn made it work:
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
viewModel.users.push({
id: csvID,
firstName: csvFirstName,
lastName: csvLastName
});
}

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