Suppose I wanted to have a text input where a user would type a product ID and press enter to load the product data into a view. I only want to load / view one product at a time.
I setup an event handler for my text input which gets the typed in product ID and then calls the read
method for the odata model:
onSubmit: function(){
var prodID = sap.ui.getCore().byId("product_id").getValue();
oData.read("/Products('" + prodID + "')", {
success: function(){
console.log(oData.getProperty("/Products('1')/Name")); // Outputs the product name
},
error: function(){}
});
},
This successfully loads the data into the model. However, the model is "keyed" (for lack of a better term) by /Products('1')
meaning that to access the data, you must know the product ID.
Where do I store the current product ID so that subsequent views know how to access the loaded product name?
I currently have a separate JSON model defined where I am storing the active product ID. In my subsequent view's onBeforeRendering
, I am reading that active product ID and then creating a new context, but this doesn't seem right.
var context = new sap.ui.model.Context(myModel, "/Products(1)");
this.getView().setBindingContext(context, "products");
Depends on what you want to do.
The standard: You have an XML view. Somewhere in your XML view you want to display the product name.
The most simple way is to bind your view to a specific product:
onSubmit: function() {
...
// assuming oData is a variable which holds your model
var sKey = oData.createKey("/Products", {
Id: prodID // Assuming Id is the name of your key property
});
this.getView().bindElement({
path: sKey,
model: "myModelName" // if your model has no name, remove this line
});
}
Then you can access the product name in your view:
<Text text="{myModelName>Name}" />
After binding the model to the view, you can always access the data (and the path) in your code using oView.getBindingContext("myModelName");
If you don't want to display the data but do some calculations: The success callback has two parameters. The first one contains the data.
oData.read(sKey, {
success: function(oResult){
...
}
});
can you expand your answer slightly to explain how you would change the binding on subsequent views? The
onSubmit
willrouter().navTo("AnotherPage")
- how do I change the binding path of the "AnotherPage" view?To me this seems like a different question. When doing navTo you should provide the necessary keys as url parameters (
.navTo("anotherPage", { Id: prodID })
. Then in your subsequent view you have a handler (Router.attachPatternMatched
) where you build a new path (createKey
and/or concatenate strings) and bind it (bindElement
)attachPatternMatched
to create anonNavTo
event in my second view's controller is exactly the piece I was missing.