cschuff
cschuff

Reputation: 5542

How to get parent View/Fragment from a Control

How can I retrieve the View/Fragment a sap.ui.core.Control belongs to?

BR Chris

Upvotes: 4

Views: 10654

Answers (2)

schnoedel
schnoedel

Reputation: 3948

You can walk up the parents until you find the View. You should however not rely on identifiers. Use the Class or Metadata to identify a View:

  buttonPress: function(oEvent){
    var b = oEvent.getSource();
    while (b && b.getParent) {
      b = b.getParent();
      if (b instanceof sap.ui.core.mvc.View){
        console.log(b.getMetadata()); //you have found the view
        break;
      }
    }
  }

Example on JSBin.

Fragments are not added to the control tree. So you cannot find them. You can however find the view they have been added to.

Upvotes: 7

matbtt
matbtt

Reputation: 4231

If the identifier of your control contains the identifier of the View (something like "__xmlview42" if you are using XML views) you could extract it and call:

sap.ui.getCore().byId("__xmlview42")

to get the containing view. If the identifier is not present you can navigate through the control tree using:

control.getParent()

until you have a control whose identifier contains the View identifier. You could also navigate through the control tree until you reach the view.

For Fragments this won't work as the content will become part of the parent View.

Upvotes: 4

Related Questions