Dynamic text in SAP Fiori Fragments

0
5954

Dear SAPLearners, in this blog post we will learn about Fragment binding in SAPUI5 or Fiori applications.

In our earlier tutorial we have introduced you to the concept of Fragments in SAPUI5/Fiori. If you have missed it, click here.

In this tutorial we will try to add the text dynamically through fragment binding. Let see how we can do this.

This is continuation to our earlier tutorial on Fragments, please refer to it before proceeding further.

1.  Follow the steps which exists in our last tutorial.

2. Revisit the code inside the Fragment file. We had declared a static text for the Text inside the Dialog like below.

Fragment in SAPUI53. Here we will dynamically pass the text to the fragments from the view controller. Here we are going to use the concept of model binding to achieve this.Go back to the view controller and write the below code to declare a model and add data to the model.

MainView.controller.js

sap.ui.controller("demofragments.MainView", {
    
    onInit: function(){
	// set model, which is used in Fragments.
	oModel = new sap.ui.model.json.JSONModel({
		myText : "Say,Hello to Fragments in SAPUI5"
	});	
	sap.ui.getCore().setModel(oModel, "myData");
    },
    
    onPress : function() {
	this._Dialog = sap.ui.xmlfragment("demofragments.fragments.Dialog",
		this);
	this._Dialog.open();
    },
    
    onClose : function() {
	this._Dialog.close();
    }
});

4. What have we done onInit() method in previous step, we have declared a JSON model and set the data to the model and assign the model to the sap.ui.getCore() for globally access across the application.

5. Now go back the dialog fragment file and slightly change the code to get the text from model.Copy and paste the below code.
Dialog.fragment.xml

<core:FragmentDefinition xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:core="sap.ui.core">
	<Dialog title="My Dialog">
		<content>
			<Text text="{myData>/myText}" />  
		</content>
		<endButton>
			<Button text="Close" press="onClose" />
		</endButton>
	</Dialog>
</core:FragmentDefinition>

6. Now save the changes and test the application, output of the application should look similar to below.

Using bindings in Fragments7. The text displayed inside the popup dialog should be same as the text defined in the model in onInit() method of the view controller.

By this we will conclude this tutorial. Stay tuned to us for more SAPUI5 tutorials.

Please feel free to comment and let us know your feedback. Subscribe for more updates.

If you liked it, please share it! Thanks!