Many times we need to show a pop up screens (Dialogs, Message Boxes etc.) to user at runtime. So in this case creating a complete view and its controller is not desirable. Hence Fragment comes into the picture.
Fragments are light-weight UI parts (UI sub-trees) which can be re-used, defined similar to Views (in XML, HTML, JS), but do not have any controller or other behavior code involved. In case code is required and for event handler methods they should be able to connect to existing controllers of the “owning” View.
So In case where someone require a set of controls to be reused in each of the view, we can utilize the capacity of fragment. We can create a fragment & can reuse everywhere we want.
For example – if we want to reuse the Product information (Below screenshot) in each of the view so in that case we can create a fragment for product information.
First view –
Second view –
Below is the step by step process to create & reuse the fragment in any SAPUI5 Project.
- Create a SAPUI5 Project.
- Create a Folder named “xml_frag” under webcontent
Creating a fragment –
- create a file under that folder with extension “fragment name”.fragment.xml
- Write the code in fragment file according to the requirement in my case I created the controls for product information.
- Create an xml view & write the below code in init method of Controller of the view to load the fragment created.
Loading a fragment & registering the fragment with action.
//import xml fragment for display
var frg = sap.ui.xmlfragment(“xml_frag.button”,sap.ui.controller(“fragment.fragment”));
In the same way in other views you can load the fragment & can pass the controller of current view & can load the fragment.
Define the fragment action in corresponding view with which fragment has been registered.
Fragments are like static controls & can be easily implemented & high reusability with actions.You can also find the detailed documentation of fragment at below –