Warm tip: This article is reproduced from stackoverflow.com, please click
odata sapui5

How to handle binding single entity with OData model

发布于 2020-04-18 09:49:51

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.

Question

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");
Questioner
Paul Wieland
Viewed
126
Marc 2020-02-05 20:45

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