Skip to main content

CRUD Operation in SAPUI5. Part 3: Fragments and Update Operation

 CRUD Operation in SAPUI5

Part 3: Fragment and Update Operation

We have covered Create and Display operation in our previous article. If you have not checked that I highly recommend you to check that before starting this article for better understanding. Link: Part 2: Create and Display

 

Fragment: Fragment is a reusable UI parts. It contains different UI elements without any controller unlike views. You can consider fragment as a sub view that contains the same use as that of the main view.

How to create a fragment?

To create a fragment first we have to create a new folder. I have created a new folder named 'fragment' inside my 'view' folder. Inside the newly created folder 'fragment' create a new file. Give the name of the file as 'details.fragment.xml'. Remember to add '<fragment name>.fragment.xml' whenever you are creating any other fragments where <fragment name> is the name of the fragment, in our case its 'detail'.

Let's start writing the code inside the fragment.

Step 1: Create a fragment with the name 'details.fragment.xml' and write the following code inside it.

- <core:FragmentDefinition xmlns="sap.m" xmlns:f="sap.ui.layout.form" xmlns:l="sap.ui.layout" xmlns:core="sap.ui.core">
- <Dialog id="helloDialog" title="Hello sapui5">
- <VBox class="sapUiSmallMargin">
- <f:SimpleForm id="SimpleFormChange354" editable="true" layout="ResponsiveGridLayout" title="Edit Details" labelSpanXL="3" labelSpanL="3" labelSpanM="3" labelSpanS="12" adjustLabelSpan="false" emptySpanXL="4" emptySpanL="4" emptySpanM="4" emptySpanS="0" columnsXL="1" columnsL="1" columnsM="1" singleContainerFullSize="false">
- <f:content>
  <Label text="Name" />
  <Input id="fginputname" />
  <Label text="Country" />
  <Input id="fginputcountry" />
  </f:content>
  </f:SimpleForm>
- <FlexBox height="100px" alignItems="Start" justifyContent="Center">
  <Button type="Emphasized" text="Submit" press="onsubmitfg" />
  </FlexBox>
  </VBox>
  </Dialog>
  </core:FragmentDefinition>
 
We have used the basic UI elements such as VBox, SimpleForm and Button. We have also added 'press' event on the button which will call the function 'onsubmitfg'. This function will update the values which is present inside the model and update it inside the table. We will write the code for this event inside View1.controller.js file.
 
Step 2: Now lets open the fragment when an entry from the table is clicked. When the entry from the table is clicked the data inside that entry will be populated inside the fragment.

In the table element in your view we have added 'selectionChange="onselectionchange"', this function will be triggered whenever we click an item inside the table. We will now write our logic inside this function. The function should be written in 'view1.controller.js'.

        onselectionchange: function(evt){
           
            var table = this.getView().byId("tabledetail");
            var index = table.indexOfItem(table.getSelectedItem());
           
            var data = sap.ui.getCore().getModel().getProperty("/details")[index];
           
            this.receiveddialog = sap.ui.xmlfragment("session1session1.view.fragment.details", this);
            this.receiveddialog.open();
           
            sap.ui.getCore().byId("fginputname").setValue(data.name);
            sap.ui.getCore().byId("fginputcountry").setValue(data.country);
           
        }
 

Initially we will pass a parameter 'evt' inside our function. This parameter need not be specified in our view. This will help us get the properties of the event and help us to determine the index of the item clicked in the table. Using the index we will be able to pull the value from the model and add it into our fragment. 

       var index = table.indexOfItem(table.getSelectedItem()); 

This will get us the index of the item clicked in the table.

      var data = sap.ui.getCore().getModel().getProperty("/details")[index];.

Then we will get the data present in the index and assign it to the variable 'data'. Using this variable we will populate the values inside our fragment. 

            this.receiveddialog = sap.ui.xmlfragment("session1session1.view.fragment.details", this);
            this.receiveddialog.open();

Here we are assigning the fragment into the variable this.receivedialog. We will be able to use this variable throughout the controller file. It will retain all the properties throught, acting like a global variable. We then open the dialog and fill in the values using setValue function.

sap.ui.getCore().byId("fginputname").setValue(data.name);
            sap.ui.getCore().byId("fginputcountry").setValue(data.country);

Since the fragment elements are not present inside our view, we can use sap.ui.getCore() to get the input elements inside our fragment and set the values.

This will be the output when you click the first element.


 
 
Step 3: Now let us write a function to allow to update the values when the submit button is pressed inside the fragment. In the fragment we have created a button with the event 'press' calling the function 'onsubmitfg'. Let us write the code inside the function.

The function should be written in 'view1.controller.js'.

        onsubmitfg: function(){
            var table = this.getView().byId("tabledetail");
            var index = table.indexOfItem(table.getSelectedItem());
           
            var fname = sap.ui.getCore().byId("fginputname").getValue();
            var fcountry = sap.ui.getCore().byId("fginputcountry").getValue();
           
            var data = {
                name: fname,
                country: fcountry
            };
           
            var array = sap.ui.getCore().getModel().getProperty("/details");
            array[index] = data;
            sap.ui.getCore().getModel().setProperty("/details",array);
            sap.ui.getCore().getModel().refresh();
           
            this.receiveddialog.destroy();
           
        }, 

 Let us discuss the code one by one. Initially I am getting the index from the table which was clicked.

Then I am getting the values from the fragment inputs for name and country and assigning them in variables fname and fcountry respectively. I am creating a json data for the same.

var fname = sap.ui.getCore().byId("fginputname").getValue();
            var fcountry = sap.ui.getCore().byId("fginputcountry").getValue();
           
            var data = {
                name: fname,
                country: fcountry
            };
 

 Now I am getting the json array from the sap.ui.getCore().getModel(). I am then updating the data present at the index of the array with the newly created data. Now set the property of the json model with the updated array and refresh it. 

            var array = sap.ui.getCore().getModel().getProperty("/details");
            array[index] = data;
            sap.ui.getCore().getModel().setProperty("/details",array);
            sap.ui.getCore().getModel().refresh();

Finally destroy all instances of the fragment or else it will throw an error for the same element id when multiple instances are created. It is always advisable to destroy the instance of fragment once the required task is completed.

            this.receiveddialog.destroy();

Once this step is completed you will be able to update the data as follows.


After the submit button is pressed the values in the table will be changed.



   Here is the full code for view1.controller.js :

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageToast",
    "sap/ui/core/Fragment"
], function(Controller, MessageToast, Fragment) {
    "use strict";

    return Controller.extend("session1session1.controller.View1", {
        onsubmit: function(){
           
            var name = this.getView().byId("inputname").getValue();
            var country = this.getView().byId("inputcountry").getValue();
            var data = {
                name: name,
                country: country
            };
            sap.ui.getCore().getModel().getProperty("/details").push(data);
            sap.ui.getCore().getModel().refresh();
        },
       
        onInit: function(){
            var initial = {
                details: [
                    {
                    name: "ui5",
                    country: "india"
                }
                ]
            };
            var omodel = new sap.ui.model.json.JSONModel(initial);
            sap.ui.getCore().setModel(omodel);
           
            var table = this.getView().byId("tabledetail");
            table.setModel(omodel);
        },
       
        onselectionchange: function(evt){
           
            var table = this.getView().byId("tabledetail");
            var index = table.indexOfItem(table.getSelectedItem());
           
            var data = sap.ui.getCore().getModel().getProperty("/details")[index];
           
            this.receiveddialog = sap.ui.xmlfragment("session1session1.view.fragment.details", this);
            // this.getView().addDependent(this.receiveddialog);
            this.receiveddialog.open();
           
            sap.ui.getCore().byId("fginputname").setValue(data.name);
            sap.ui.getCore().byId("fginputcountry").setValue(data.country);
           
        },
       
        onsubmitfg: function(){
            var table = this.getView().byId("tabledetail");
            var index = table.indexOfItem(table.getSelectedItem());
           
            var fname = sap.ui.getCore().byId("fginputname").getValue();
            var fcountry = sap.ui.getCore().byId("fginputcountry").getValue();
           
            var data = {
                name: fname,
                country: fcountry
            };
           
            var array = sap.ui.getCore().getModel().getProperty("/details");
            array[index] = data;
            sap.ui.getCore().getModel().setProperty("/details",array);
            sap.ui.getCore().getModel().refresh();
           
            this.receiveddialog.destroy();
           
        }
     });
}); 

Conclusion:

We have learnt to perform create, update and display operation in sapui5. I would highly recommend to follow all the parts and try to explore more. I would love to hear the feedback from you! Thanks for reading till the end of the article. 

Comments

Popular posts from this blog

How to format HTML/CSS/JS (or any other) using node.js in Notepad++ in simply easy steps.

Hey guys! Today I am going to tell you on how to use code format / pretty print your HTML / CSS / JS or any other programming language using node modules (Prettier) in notepad++. Before. After. Lets get started! Pre-requisite: you need to have node installed in your computer. You can download it from here . Make sure you have installed node correctly. install notepad++ in your computer. You can download the latest version from here . Step 1. Install Prettier using node. To install Prettier in your system click on Start => cmd. This will open Command prompt. Write this command in Command Prompt.  npm install --save-dev --save-exact prettier To check if prettier is installed correctly type. prettier --check for more info click here. Step 2. Check if nppexec plugin in set in your notepad++ Mostly notepad++ comes with nppexec  by default. Just in case you cannot find nppexec. Check out this amazing blog that tells you step by step how to set up nppexec in your notepad++....

CRUD Operation in SAPUI5 Part 2: Create and Display using Input and Table

 CRUD Operation in SAPUI5 Part 2: Create and Display in Table In my previous article we discussed the brief introduction about SAPUI5, MVC architecture and we developed a simple user interface with input and tables. In this article we will discuss the Model and Controller from the MVC architecture. If you have not seen the first part I highly recommend you to see that first. Link:  Part 1: Intro and UI Design