Search code examples
sapui5

SAPUI5 Using the same Controller for two Views


I recently developed an SAPUI5 app for the Fiori Launchpad and am looking to convert the same app to also be Freestyle Portal usable and individually stylable, so I need a second View.

The problem is I have the task to use the same Logic aka. Controller for both Views. I've tried using routing, but I cant seem to find a solution, that's working for me, so I would welcome any suggestions how to tackle this task.

I am also really new to SAPUI5 so it might be that I am overlooking an easy solution so please be considerate.

With regards Mathias


Solution

  • Please check the SAPUI5 SDK Documentation for the class sap.ui.core.mvc.controller method extend.

    You could define a class based on the UI5 Standard sap.ui.core.mvc.controller using the extend method to create a controller that contains the common functions needed by both views. Then you could defined two controllers using extend on the common controller. Now you would have two controllers containing the common functions and have the possibility to add view specific functions.

    Note that NO separate namespaces are created.

    Here is the outline of the structure that you would create.

    Common Controller: BaseController.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        ... //Other classes needed
    ], function (Controller, ..) {
        "use strict";
        return Controller.extend("yourApp.controller.BaseController", {
            someMethod: function () {
                ....
            },
        });
    });
    

    Specific Controller for one view ViewOneController.js

    sap.ui.define([
        "yourApp/controller/BaseController",
        ... //Other classes needed
    ], function (myBaseController, ..) {
        "use strict";
        return myBaseController.extend("yourApp.controller.ViewOneController", {
            someMethod2: function () {
                ....
            },
        });
    });