SAPUI5 display Message Toast

In this article we learn how to display message toast in SAPUI5 using sap.m.MessageToast.

Code a Button control in the view.xml file. On the click of button, we call a function to display the message toast.

<Button id="_IDGenButton1" text="Press the button"
	 		   press=".onPress"/>

Code a Button control in the view.xml file. On the click of button, we call a function to display the message toast. Create function in the controller.js file and implement message toast code.

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageToast"
],
    /**
     * @param {typeof sap.ui.core.mvc.Controller} Controller
     */
    function (Controller,MessageToast) {
        "use strict";

        return Controller.extend("amarmn.sapui51.controller.View1", {
            onInit: function () {

            },
            onPress: function () {
                MessageToast.show("This is the message toast!!!");
            }
        });
    });

Alternate code : Instead of loading MessageToast using function sap.ui.define(), we can load the module using sap.ui.require(). This might help in performance improvement as the module will be loaded when required.

sap.ui.define([
    "sap/ui/core/mvc/Controller"
],
    /**
     * @param {typeof sap.ui.core.mvc.Controller} Controller
     */
    function (Controller) {
        "use strict";

        return Controller.extend("amarmn.sapui51.controller.View1", {
            onInit: function () {

            },
            onPress: function () {
                sap.ui.require(["sap/m/MessageToast"], 
                               function (oMessage) {
                                 oMessage.show("This is the message toast-2!!!");
                });
            }
        });
    });
 

Alternate code : It is also possible to pass the text from the view.xml file. This text will be received in the controller file and then displayed as Message Toast.

<Button id="_IDGenButton1" text="Press the button"
				 		press=".onPress('from view file!!!')"/>
onPress: function (sValue) {
                sap.ui.require(["sap/m/MessageToast"], function (oMessage) {
                    oMessage.show(sValue);
                });
            }

Alternate code : You can display Message Toast by writing code directly in the view file.

<Button id="_IDGenButton1" text="Press the button"
	press="sap.m.MessageToast.show('Directly from the view file...!!')"/>