njames
njames

Reputation: 386

Pass another controller when instantiating a fragment in SAPUI5

In the SAPUI5 / OpenUI5 xmlfragment documentation the third parameter is a controller for handling actions from the fragment.

This is critical for a dialog fragment where there are buttons to press etc.

Most of the time I have seen this instantiated as this or sap.ui.getCore().byId('<element>').getController())

See an example at Fragment not get correct Controller

Because of the complexity in a particular dialog I would like to have a separate controller for it.

I have looked around at this and had a few attempts but so far not successful.

I have put a working example on github of using this.

But I would like to instantiate Dialog.js as the controller for the Dialog.fragment.xml from initial.view.controller

Any takers?

Pull requests gladly received.

The Crux of the example is as follows (this is the initial.controller.js) :

sap.ui.controller("sc.test.view.initial", {

oDialog: null,

openTestDialog: function(){
    console.log("in open dialog");
     // instantiate the other controller
     var oDialogController = new sc.test.view.Dialog();
    // this next commented line is the 'normal' way to do it
    // oDialog = new sap.ui.xmlfragment( "sc.test.view.Dialog", this);  //oDialogController);
    // this is what I would like to achieve
    oDialog = new sap.ui.xmlfragment( "sc.test.view.Dialog", oDialogController);
    oDialog.open();
},       


onCartDialogCancel:function(oEvent){
// this function would then be in the other controller but how to get a handle on the dialog?
    oDialog.close();

}

});

Thanks.

Upvotes: 6

Views: 14453

Answers (3)

KynanJ
KynanJ

Reputation: 21

I copied an existing controller.js, and renamed it.

Then, instantiated that as a below, and passed it through with the fragment.

var oNewController = new sap.ui.core.mvc.Controller("myProject.DialogController"); this._oDialog = sap.ui.xmlfragment("myPopup","myProject.fragments.myPopup", oNewController);

All eventing is now handled in oNewController, rather than the previously used "this"...

Upvotes: 2

qmacro
qmacro

Reputation: 3105

(Just got to SYD airport)

All you're missing is the

jQuery.sap.require("sc.test.view.Dialog");

in your initial.controller.js.

Pushed a quick fix in a branch to your repo and opened a PR

Upvotes: 2

Jasper_07
Jasper_07

Reputation: 2473

only example i could find close to yours was in the Material Shortage Fiori app

  oCtrl = sap.ui.controller("myapp.fragments.DirectCallDialog");
  oDirectCallDialog = sap.ui.xmlfragment("myapp.fragments.DirectCallDialog", oCtrl);

lots of examples of injecting a controller when the fragment was called from a helper class. The helper class promotes reuse, eg same dialog fragment can be called from multiple views/components. The helper class method for the dialog setup is called from within a controller and the oController parameter is set to 'this'.

hth jsp

Upvotes: 2

Related Questions