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

Difference between this.getView().byId and this.byId

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 (Rarely used)*

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, instead of passing a plain string literal only (e.g. new Panel("myPanel")), use the API createId:

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.

* One of the valid use cases for sap.ui.getCore().byId is when accessing the currently focused control of which the ID was retrieved by calling getCurrentFocusedControlId().

More about IDs


SAP Fiori elements guidelines

When developing Fiori elements extensions, make sure to adhere to the documented compatibility guidelines, especially regarding byId:

[…] Don’t access or manipulate SAP Fiori elements’ internal coding.
[…] Must not access any UI elements that are not defined within your view extensions.

⚠ Caution
If you do not adhere to this guideline, your app may not work with future SAPUI5 versions because SAP Fiori elements might exchange controls for new ones that have a different API.

Leave a Comment