SAPUI5: Retrieve model object in controller

Marc picture Marc · Aug 20, 2015 · Viewed 25.3k times · Source

I have a master-detail application that consumes an OData service (declared in manifest.json).

In the detail controller, I bind the model to the view in the following way (this method is attached to a router object).

_onObjectMatched: function(oEvent) {
    this.getView().bindElement({
        path: "/ContractCompSet('" + oEvent.getParameter("arguments").id + "')",
        model: "contracts"
    });
}

How can I access the actual bound model object from within this controller?

Closest I got (but seems too be a little too complicated) is as follows

var path = this.getView().getElementBinding('contracts').sPath.substring(1);
var model = this.getView().getModel('contracts').oData[path];

Answer

Carsten picture Carsten · Aug 20, 2015

Well your approach isn't to far off and is indeed pretty much the same as hirses.

The point is the binding does not contain "just" the bound model object. It contains the information about model, path to the "bound object" and context. These can be retrieved from the binding. To access the "bound object" you then have basically two paths available.

Get the model and path from the binding and access the "bound object" via the model: (this is what you and hirse outlined)

var path = this.getView().getElementBinding('contracts').sPath;
var boundObject = this.getView().getModel('contracts').getProperty(path);

Or get the context and path and access the "bound object" that way:

var context = this.getView().getElementBinding('contracts').oContext;
var boundObject = context.getProperty(context.getPath());

Without having done to much research into this I would prefer the second option. It just seems more along the line of how the context binding is intended.