Difference Between this.getView().byId(), this.byId(), and sap.ui.getCore().byId()

Solution 1:

About this.getView().byId and this.byId (Recommended)

Take a look at the source code of the this.byId method:

// sap.ui.core.mvc.Controller
Controller.prototype.byId = function(sId) {
  return this.oView ? this.oView.byId(sId) : undefined;
};

As you can see, this.byId is just a shortcut for this.getView().byId. They both can be used to access controls defined in the view. E.g.:

<!-- Given -->
<Panel id="myPanel" />
myControllerMethod() {
  const thatPanel = this.byId("myPanel"); // === this.getView().byId("myPanel")
},

About sap.ui.getCore().byId (Don't use it)

The API sap.ui.getCore().byId(/*...*/) on the other hand, awaits a fully concatenated global ID which is why you cannot simply exchange this.byId with sap.ui.getCore().byId if the target control is a view descendant.

sap.ui.getCore().byId("__xmlview0--myPanel"); // <-- Avoid concatenating ID parts!

Generally, sap.ui.getCore() should be avoided when developing UI5 applications that would be added to Fiori launchpad (FLP). I.e. when instantiating a control in the controller, keep in mind to use the API createId:

new Panel("myPanel");

new Panel(this.createId("myPanel")); // Makes it accessible via this.byId("myPanel")

From the topic "JavaScript Coding Issues" section "Don't create global IDs":

[...] you must not create stable IDs for your controls, fragments, or views in OpenUI5. Doing so might result in duplicate ID errors that will break your app. Especially when running together with other apps, there could be name clashes or other errors.

Use the createId() function of a view or controller instead. This is done automatically in XMLViews and JSONViews. The createId() function adds the View ID as a prefix, thus recursively ensuring uniqueness of the ID.

More about IDs

  • Stable IDs: All You Need to Know
  • For the sake of completeness: How to Access Elements from XML Fragment by ID