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

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

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.

How to traverse JSON model?

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).

How to dynamically bind an existing OpenUI5 Combobox?

I'm evaluating OpenUI5 and I'm not clear about the binding concept.
In a XML login view, I have a Combobox that I want to populate after a successful login:
<ComboBox id="cboJoraniInstance" enabled="false" />
So, into my controller I've created an Ajax call with a parameter:
return Controller.extend("sap.ui.jorani.wt.controller.Login", {
onCheckEmail : function () {
var oDialog = this.getView().byId("BusyDialog");
oDialog.open();
var sMail = this.getView().byId("txtEmail").getValue();
var oListInst = this.getView().byId("cboJoraniInstance");
var aData = jQuery.ajax({
type : 'POST',
url : 'http://localhost/dummy/getJoraniInstances.php',
data: {
mail: sMail
},
async: false,
success : function(data,textStatus, jqXHR) {
//Link Combobox
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
oListInst.setModel(oModel);
oListInst.bindElement("/Instances");
oListInst.bindProperty("value", "Url");
oListInst.bindProperty("name", "name");
oListInst.setEnabled();
},
error: function (jqXHR, textStatus, errorThrown){
MessageToast.show('An error occured');
}
});
oDialog.close();
},
});
The call to my web service is OK and returns:
{
"Instances": [{
"Name": "Local",
"IsDefault": true,
"Url": "http:\/\/localhost\/jorani\/"
}, {
"Name": "D\u00e9mo",
"IsDefault": false,
"Url": "https:\/\/demo.jorani.org\/"
}]
}
The code executes without error, but the control is not filled by my binding attempts.
I've checked the various SO questions on this topic and they all add a new ComboBox into the view dynamically, for example:
oListInst.placeAt("content");
But that is not what I want to achieve, I'd like to fill an existing object. Is it possible?
Concerning the view, if I fill the Combobox with the code below, it is working fine (but it doesn't use the binding feature):
$.each(data.Instances, function(i, obj) {
oListInst.addItem(new sap.ui.core.ListItem({key:obj.Url, text:obj.Name}));
});

jsTree: with lazy loading the plugin "dnd" is not working

I'm using jsTree (latest version) in my web app. I have a lot of nodes to display in the tree, so I am using lazy loading otherwise I would run into a time out.
When the tree is loaded, the user can pick values from a second tree and move them into the lazy loaded tree (jsTree plugin "dnd"). Both tree have the jsTree plugin "dnd" installed. But I can not drop a element into the lazy loaded tree, when I try to do so the node to be dropped is having an icon with a red cross (indication: not allowed here).
This is the code for the lazy loaded tree:
$('#target_tree').jstree({
'core' : {
'data' : {
"url" : "get_current_hierachy",
"data" : function (node) {
return {'p_parent_id': node.id};
},
"dataType": "json",
"check_callback": true
}
},
"plugins" : ["dnd"]
});
When I load some data in the first tree without the lazy loading, the drag'n'drop is working as expected.
When I load data in the first tree with lazy loading, the drag'n'drop is not working any more.
Any help would be greatly appreciated.
Try this ...
$(document).ready(function () {
$('#target_tree').jstree({
'core': {
'data': {
"url": function (node) {
var url;
if (node.id == '#') {
url = "getRootNode";
} else {
var id = $(node).data("id");
url = "getChildNode?nodeid=" + id;
}
return url;
},
"data": function (node) {
return { "id": node.id };
},
"type": "GET",
"dataType": "json",
"contentType": "application/json charset=utf-8",
},
'check_callback': true,
},
"plugins": ["dnd"]
});
});
I think you need to prepare url

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="
}
}
]