How to traverse JSON model? - sapui5

Image
Controller.js
item: function(evt) {
var list = sap.ui.getCore().byId('appListId');
var sItem = list.getSelectedItem();
var oBindingContext = sItem.getBindingContext('products');
var sPath = oBindingContext.sPath;
console.log(sPath); // get path /collection/0/App/0
var context = sap.ui.getCore().byId("appListId").getModel('products')
.getContext(sPath);
var start = sPath.lastIndexOf("/") + 1;
var appIndex = sPath.substring(start, sPath.length);
this.router.navTo("selectedAppRecord", {
catIndex : this.subCatIndex,
appIndex : appIndex
});
}
Path of JSON Array :
get this path /collection/0/App/0
I have an JSON array :
{
"collection": [{
"model": "08 Report Fraud",
"App": [{
"App": "COUNCIL001",
"description": "Benefit Fraud",
"module": "08 Report Fraud",
"iConClass": "icon-devil",
"UserSpecific": "Yes"
}]
}]
}
finally my goal is how to get this UserSpecific key in control side.

You can use the getProperty function of the BindingContext to get relative properties.
var oItem = sap.ui.getCore().byId('appListId').getSelectedItem();
oItem.getBindingContext('products').getProperty('UserSpecific');
In your handler function I would recommend to get the current item from the event:
oEvent.getSource() || oEvent.getSource().getSelectedItem()
Depending on the type of event (ListItem#select or List#selectionChange).

Related

Unable to access control, created in JSView, from controller with View byId

I am trying to display a VizFrame and my data are in a simple JSON format.
Both my view and controller are in JS. (I will start writing my view in XML going forward) because I see that is the way to go.
I get a blank page with the error: "setDataset of undefined". What am I missing?
My view code is this.
createContent: function(oController) {
var oSubHeader = new sap.m.Bar({
contentLeft: [
new sap.m.Button({
icon: "sap-icon://nav-back",
press: [oController.onNavBack, oController]
})
],
contentMiddle: [
new sap.m.Label({
text: "{i18n>app_subhead_2}"
})
]
});
var oVizFrame = new sap.viz.ui5.controls.VizFrame("VizFrameId", {
width: "100%",
height: "400px",
vizType: "line"
});
var oPage = new sap.m.Page({
title: "UI5 Assignment App",
showSubHeader: true,
subHeader: oSubHeader,
content: [oVizFrame]
});
return oPage;
}
My corresponding controller is
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/core/UIComponent",
"sap/ui/core/routing/History",
"sap/viz/ui5/controls/VizFrame",
"sap/viz/ui5/data/FlattenedDataset"
], function (Controller, UIComponent, History, VizFrame, FlattenedDataset) {
"use strict";
return Controller.extend("Project_Tile_learning.Divya_tile_Project.controller.ProductDetailPage", {
onNavBack: function () {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("homepage", true);
}
},
onInit: function () {
var sampleDatajson = new sap.ui.model.json.JSONModel("json/PA.json");
var oVizFrame = this.getView().byId("VizFrameId");
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions: [{
name: "Year",
value: "{Year}"
}],
measures: [{
name: "Supplier",
value: "{Supplier}"
}, {
name: "Liquor",
value: "{Liquor}"
}, {
name: "Quantity",
value: "{Quantity}"
}],
data: {
path: "/items"
}
});
oVizFrame.setDataset(oDataset);
oVizFrame.setModel(sampleDatajson);
var oFeedValueAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
"uid": "valueAxis",
"type": "Measure",
"values": ["Supplier"]
});
var oFeedValueAxis1 = new sap.viz.ui5.controls.common.feeds.FeedItem({
"uid": "valueAxis",
"type": "Measure",
"values": ["Liquor"]
});
var oFeedValueAxis2 = new sap.viz.ui5.controls.common.feeds.FeedItem({
"uid": "valueAxis",
"type": "Measure",
"values": ["Quantity"]
});
var oFeedCategoryAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
"uid": "categoryAxis",
"type": "Dimension",
"values": ["Year"]
});
oVizFrame.addFeed(oFeedValueAxis);
oVizFrame.addFeed(oFeedValueAxis1);
oVizFrame.addFeed(oFeedValueAxis2);
oVizFrame.addFeed(oFeedCategoryAxis);
}
});
});
Update: JS View is deprecated since UI5 v1.90. Use Typed View instead.
When creating a control in JS view definition, always use this.createId("myControl").
From the doc:
If you want to define IDs for controls inside a JSView to guarantee their uniqueness [...], you cannot give hardcoded IDs, but have to give the view the opportunity to add its own instance ID as a prefix. This is done by using the View.createId(...) method.
For the example above, this is done as follows:
new sap.viz.ui5.controls.VizFrame(this.createId("VizFrameId"), { /*...*/ });
Then in the controller, myView.byId tries to access the control with view's own ID as a prefix, which will succeed this time since the control has an ID with the view ID as a prefix.

Rearrrange populated json result in mongoose

A simple json response for Post.find().populate("name") will return json result as follow. Note: The focus of the question is to rearrange the "name":"Alex" in json to the final structure as shown. Ignore the part that need hiding _id and __v. Thanks.
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"postedBy": {
"_id": "54cd6669d3e0fb1b302e54e4",
"name": "Alex",
"__v": 0
},
"__v": 0
},
...
]
How could i rearrange and display the entire json as follow?
[
{
"_id": "54cd6669d3e0fb1b302e54e6",
"title": "Hello World",
"name": "Alex"
},
...
]
You can use the lean() method to return a pure JSON object (not a mongoose document) that you can then manipulate using lodash helper methods such as map(), like in the following example:
Post.find()
.populate("name")
.lean().exec(function (err, result) {
if(result){
var posts = _.map(result, function(p) {
p.name = p.postedBy.name;
p.postedBy = undefined;
return p;
});
console.log(posts);
}
});
You can disable the "__v" attribute in your Schema definitions by setting the versionKey option to false. For example:
var postSchema = new Schema({ ... attributes ... }, { versionKey: false });
As follow-up to your question on rearranging the order of the properties in the JSON, JS does not define the order of the properties of an object. However, you
can use both the JSON.parse() and JSON.stringify() methods to change the order, for example
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
console.log(json);
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
console.log(k);
Check the demo below.
var json = {
"name": "Alex",
"title": "Hello World",
"_id": "54cd6669d3e0fb1b302e54e6"
};
//change order to _id, title, name
var changed = JSON.parse(JSON.stringify(json, ["_id","title","name"] , 4));
pre.innerHTML = "original: " + JSON.stringify(json, null, 4) + "</br>Ordered: " + JSON.stringify(changed, null, 4);
<pre id="pre"></pre>

UI5 Tree Binding to JSON

I have the following JSON file.
"idocs": [
{
"Docnum": "00063463",
"Mestyp": "MATMAS",
"Status": "53",
"Sndprn": "EXTSYS1",
"Direct": "Inbound",
"Message": "Material 00002342 Created",
"messages": [{
"message": "Material 00002342 Created"
}],
"segments": [{
"segment": "E1MARAM",
"fields": [{
"fieldName": "MATNR"
}]
}]
}
I want to bind this to a tree node. I have the following code to "attempt" to do this and it is not doing anything. Not even an error.
var oTree = new sap.ui.commons.Tree("tree")
.placeAt("idViewRoot--idViewDetail--toolBar-content");
oTree.bindAggregation("nodes", tgtPath, function(
sId, oContext) {
alert("stuff");
var treePath = oContext.getPath();
var bindTextName = '';
if (treePath.indexOf("fields") !== -1) {
bindTextName = "fieldName";
} else {
bindTextName = "segment";
}
return new sap.ui.commons.TreeNode()
.bindProperty("text", bindTextName);
});
I would appreciate if someone could take a look and point me in the right direction.
Should I see an alert "stuff" appearing, because I do not even see that. Could it be an issue with the binding.
The value of tgtPath is /idocs/0/segments.
Martin
// data has to be tree structured
var oData = {
root:{
name: "root",
0: {
name: "item1",
0: {
name: "subitem1",
0: {
name: "subsubitem1"
},
1: {
name: "subsubitem2"
}
},
1: {
name: "subitem2",
0: {
name: "subsubitem3"
}
}
},
1:{
name: "item2",
0: {
name: "subitem3"
}
}
}
};
var oModel = new sap.ui.model.json.JSONModel();
// set the data to the model
oModel.setData(oData);
var oTree = new sap.ui.commons.Tree("tree");
oTree.setWidth("100%");
// set the model to the tree
oTree.setModel(oModel);
var oTreeNodeTemplate = new sap.ui.commons.TreeNode("node");
oTreeNodeTemplate.bindProperty("text", "name");
oTreeNodeTemplate.setExpanded(true);
oTree.bindAggregation("nodes", "/root", oTreeNodeTemplate);
oTree.placeAt("body");
Here is sample https://jsbin.com/rexahoquso/edit?html,js,output

How do I pass a JSON object from one controller to another(/view to view)?

I want to pass a JSON object from one controller to another. How do I do that?
Or can I pass a oModel to the other view? If so how do I do that?
Thanks
If you store your data in a global model:
var oData = <your JSON data>;
var oModel = new sap.ui.model.json.JSONModel(oData);
sap.ui.getCore().setModel(oModel);
it can then be accessed from any other controller/view in your application context
one solution is that you use sap.ui.core.EventBus. Basically you can pass any object from one controller to another including JSONModel using subscribe and publish.
To add to Qualiture's answer:
If you wanted to attach a specific model to a specific view, which your question sounds like a little, you can do just that by going:
view.setModel(oModel);
Cheers
Michel
yes,you can pass string,object and Array from one view to another through the Navigation.
enter code here
enter code here for controller
handleLinkPress: function(oEvent) {
try {
var array = [];
var obj = {
"Delivery": "80000095",
"DelvNo": "80000095",
"Date": "2018-01-04T00:00:00.000Z",
"Priority": "00",
"LoadDate": "2018-01-04T00:00:00.000Z",
"PickDate": "2018-01-04T00:00:00.000Z",
"ShippingPoint": "0001",
"Route": "",
"LoadingPoint": "01",
"ShipTo": "CUSTOMER",
"SoldTo": "CUSTOMER"
};
array.push(obj);
if (obj !== null) {
sap.ui.core.UIComponent.getRouterFor(this).navTo("Route", {
RouteData: JSON.stringify(array)
});
}
} catch (e) {
console.error("Error : " + e.message);
sap.m.MessageBox.show(e.message, {
icon: sap.m.MessageBox.Icon.ERROR,
title: "Error",
actions: [sap.m.MessageBox.Action.OK],
defaultAction: sap.m.MessageBox.Action.OK,
styleClass: "sapUiSizeCompact",
contentWidth: "150px"
});
}
}
Code for manifest.json
{
"pattern": "Route/{RouteData}",
"name": "Route",
"targetControl": "masterView",
"viewId": "Route",
"viewName": "Route"
}
code for the controller where you get that Array which you want pass
handleCloseRoutePress: function(oEv)
{
var sRouteData=JSON.parse(oEv.getParameter("arguments").RouteData);
}

How to get all versions of an object in Google cloud storage bucket?

In a web page hosted in Google cloud storage, I will like to show revision history, which require listing all versions of the object.
Sending GET request to the bucket with ?versions parameter return list versions all objects. Is there any way to list all versions of a single object, as in gsutil ls -la, in javascript?
There is not. The closest you can do is to use versions=true and prefix=YOUR_OBJECT_NAME.
GCS will respond with a listing of objects beginning with all of the versions of your object and continuing on to any other objects that begin with YOUR_OBJECT_NAME. You'll have to check those items to see when the listing runs out of versions of your object and moves on to other objects.
If it so happens that only one object begins with YOUR_OBJECT_NAME (for example, your object is "foo.txt" and there are no files named, say, "foo.txt.backup", you will get exactly the files you want. You probably don't want to rely on this as a general practice, though.
Brondon's answer work with XML, but not with gapi client.
/**
* Get versions meta data of the object.
* #return {goog.async.Deferred} return history of the object.
*/
mbi.data.Object.prototype.history = function() {
var df = new goog.async.Deferred();
var use_gapi = true;
var name = this.getName();
if (use_gapi) {
// GAPI does not return result for versions request.
var params = {
'bucket': this.getBucketName(),
'versions': true,
'prefix': name
};
// console.log(params);
var req = gapi.client.rpcRequest('storage.buckets.get',
mbi.app.base.GAPI_STORAGE_VERSION, params);
req.execute(function(json, row) {
if (json) {
df.callback(json);
} else {
df.errback();
throw new Error(row);
}
});
} else {
var xm = mbi.data.Object.getXhr();
var uri = new goog.Uri(this.getUrl());
uri.setParameterValue('versions', 'true');
uri.setParameterValue('max-keys', '25');
uri.setParameterValue('prefix', name);
var url = uri.setPath('').setFragment('').toString();
xm.send(url, url, 'GET', null, {}, 1, function(e) {
var xhr = /** #type {goog.net.XhrIo} */ (e.target);
if (xhr.isSuccess()) {
var xml = xhr.getResponseXml();
// console.log(xml);
var json = mbi.utils.xml.xml2json(xml);
var items = json['ListBucketResult']['Version'];
var versions = goog.isArray(items) ? items : items ? [items] : [];
versions = versions.filter(function(x) {
return x['Key'] == name;
});
df.callback(versions);
} else {
df.errback(xhr.getStatus() + ' ' + xhr.getResponseText());
}
});
}
return df;
};
GAPI return as follow without version meta:
[
{
"id": "gapiRpc",
"result": {
"kind": "storage#bucket",
"id": "mbiwiki-test",
"name": "mbiwiki-test",
"timeCreated": "2013-08-20T01:18:46.957Z",
"metageneration": "9",
"owner": {
"entity": "group-00b4903a97262a358b97b95b39df60893ece79605b60280ad389c889abf70645",
"entityId": "00b4903a97262a358b97b95b39df60893ece79605b60280ad389c889abf70645"
},
"location": "US",
"website": {
"mainPageSuffix": "index.html",
"notFoundPage": "error404.html"
},
"versioning": {
"enabled": true
},
"cors": [
{
"origin": [
"http://static.mechanobio.info",
"http://mbinfo-backend.appspot.com",
"https://mbinfo-backend.appspot.com",
"http://localhost",
"chrome-extension://pbcpfkkhmlbicomenogobbagaaenlnpd",
"chrome-extension://mhigmmbegkpdlhjaphlffclbgkgelnbe",
"chrome-extension://jhmklemcneaienackijjhdikoicmoepp"
],
"method": [
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"PATCH"
],
"responseHeader": [
"content-type",
"Authorization",
"Cache-Control",
"x-goog-meta-reviewer"
]
}
],
"storageClass": "STANDARD",
"etag": "CAk="
}
}
]