Showing posts with label sapui5. Show all posts
Using Parts in formatters to pass multiple fields

Using Parts in formatters to pass multiple fields

Sanjo Thomas•03:14:00

When working with SAPUI5, it's common to use formatters to manipulate data before it's displayed on a view. One challenge that developers often face is passing multiple fields to a formatter function. Fortunately, this can be easily achieved by using parts.



Parts are essentially placeholders that can be used to represent different binding paths in a formatter function. By using parts, you can pass any number of fields to a formatter function, making it much more flexible and powerful.

To use parts in a formatter function, you need to define them in the XML view where the formatter is being used. Here's an example:

```

<Text text="{parts: [{path: 'firstName'}, {path: 'lastName'}], formatter: '.fullNameFormatter'}" />

```

In this example, we're using a Text control and binding its text property to the result of a formatter function called `fullNameFormatter`. We're also defining two parts using the `parts` property. The first part refers to the `firstName` field, and the second part refers to the `lastName` field.


To access these parts in the formatter function, you can use the `parts` parameter. This parameter is an array that contains all the parts defined in the view, in the order they were defined. Here's an example of a formatter function that uses parts to concatenate the first and last names:


```

fullNameFormatter: function(firstName, lastName) {

  var firstName = firstName;

  var lastName = lastName;

  return firstName + ' ' + lastName;

}

```


In this function, we're using the both parameter values to retrieve the values of the first and last name parts, and then concatenating them with a space in between.


Using parts in SAPUI5 formatters is a powerful technique that can greatly enhance the flexibility and functionality of your applications. By defining parts in your views and accessing them in your formatter functions, you can pass any number of fields to your formatter and manipulate them in a variety of ways.

Read more
Handling batch requests using OData V4 in Sapui5

Handling batch requests using OData V4 in Sapui5

Sanjo Thomas•03:37:00

Batch operations in OData v4 allow multiple requests to be sent to the server as a single request, reducing the number of round trips required and improving performance. In this blog, we will discuss how to handle batch operations in OData v4 with context to SAPUI5.



To begin with, let's understand what batch operations are. Batch operations allow multiple requests to be bundled together and sent to the server as a single request. This can include GET, POST, PUT, PATCH, and DELETE requests. The server processes each request in the batch and returns a response for each individual request.


In SAPUI5, batch operations can be handled using the `sap.ui.model.odata.v4.ODataModel` class. To enable batch operations, set the `useBatch` property to `true` when creating an instance of the `ODataModel` class.


```

var oModel = new sap.ui.model.odata.v4.ODataModel({

    serviceUrl: "/sap/opu/odata/sap/Z_MY_SERVICE_SRV/",

    useBatch: true

});

```


Once batch operations are enabled, multiple requests can be added to a batch using the `addBatchChangeOperations` method. This method takes an array of requests to be added to the batch.


```

var oRequest1 = oModel.createBatchOperation("/Products", "POST", oData1);

var oRequest2 = oModel.createBatchOperation("/Products", "POST", oData2);

oModel.addBatchChangeOperations([oRequest1, oRequest2]);

```


In this example, two POST requests are added to the batch, one to create a new product with `oData1` data and another to create a new product with `oData2` data.


Once all requests have been added to the batch, the `submitBatch` method can be called to send the batch request to the server.


```

oModel.submitBatch(function(oResponse) {

    // Handle response here

}, function(oError) {

    // Handle error here

});

```


In the success callback function, the `oResponse` parameter contains an array of responses for each individual request in the batch. In the error callback function, the `oError` parameter contains the error response for the entire batch request.


In conclusion, batch operations in OData v4 can be easily handled in SAPUI5 using the `sap.ui.model.odata.v4.ODataModel` class. By enabling batch operations and adding multiple requests to a batch, performance can be improved by reducing the number of round trips to the server.

Read more
OData V2 and V4 in Connect with SAPUI5

OData V2 and V4 in Connect with SAPUI5

Sanjo Thomas•03:27:00

SAPUI5 is a popular web application development framework that allows developers to create efficient and responsive web applications. One of the key features of SAPUI5 is its support for OData, a protocol for building and consuming RESTful APIs. OData has evolved over time, and the latest version is OData V4. In this blog, we will discuss the differences between using OData V2 and OData V4 models in SAPUI5.



OData V2 vs OData V4:

OData V2 is the older version of OData, while OData V4 is the latest version. One of the main differences between the two versions is the structure of the payload. OData V2 uses Atom and JSON formats, while OData V4 uses JSON only. OData V4 also provides better support for complex types and improves the performance of the payload.

Another key difference between the two versions is the way they handle server-side operations. OData V2 relies on the SAP Gateway for server-side operations, while OData V4 offers more flexibility in terms of server-side operations. OData V4 provides support for server-side filtering, sorting, and paging, which makes it easier for developers to build performant applications.

In terms of data binding, OData V4 offers a simplified syntax for data binding, which makes it easier for developers to bind data to UI elements. OData V4 also provides better support for batch requests, which can improve the performance of applications that require multiple server requests.

OData V4 also offers better support for metadata. In OData V2, the metadata is embedded in the payload, which can cause performance issues for large payloads. In OData V4, the metadata is separated from the payload, which improves the performance of large payloads.


One of the main advantages of using OData V4 in SAPUI5 is its support for annotations. Annotations allow developers to add additional metadata to the OData service, which can be used to provide additional information to the UI elements. Annotations can also be used to define custom UI elements, which can improve the user experience of the application.


Both OData V2 and OData V4 have their advantages and disadvantages. OData V2 is simpler to use and provides better support for legacy systems, while OData V4 offers better performance and more flexibility in terms of server-side operations. Ultimately, the choice between the two versions will depend on the specific needs of the application. However, given the advantages of OData V4 in terms of performance and flexibility, it is likely that more developers will migrate to OData V4 in the future.

Read more
Check SAPUI5 version in a SAP Fiori App

Check SAPUI5 version in a SAP Fiori App

Sanjo Thomas•03:40:00

SAP Fiori is a popular user interface (UI) framework used in SAP applications. It is built on top of SAP UI5, which is a client-side JavaScript library that provides a rich set of UI controls and features. In order to keep your SAP Fiori applications up-to-date and ensure compatibility with the latest SAP UI5 libraries, it's important to know how to check the SAP UI5 version in SAP Fiori.



Here are a few ways to check the SAP UI5 version in SAP Fiori:

1. Check the SAPUI5 Version using the SAPUI5 Version Info App

SAP provides an SAPUI5 Version Info App, which is a Fiori app that displays the current version of SAPUI5 that is being used in the system. To access the app, go to the SAP Fiori launchpad and search for the "SAPUI5 Version Info" app. Once you launch the app, the version of SAPUI5 being used will be displayed.


2. Check the SAPUI5 Version using the Browser Developer Tools

Another way to check the SAP UI5 version is to use the browser developer tools. To do this, first load the SAP Fiori application you want to check the UI5 version for in your browser. Once the application is loaded, open the browser developer tools (usually by pressing F12) and navigate to the Network tab. In the network tab, look for a request to the SAPUI5 library (usually named "sap-ui-core.js"). Click on the request and the response will show the version of SAPUI5 being used by the application.


3. Check the SAPUI5 Version using the SAPUI5 Library Information Page

Finally, you can also check the SAP UI5 version using the SAPUI5 library information page. To access this page, navigate to the following URL in your browser: 

https://<your system URL>/sap/public/bc/ui5_ui5/sap/<your SAPUI5 version>/test-resources/sap-ui-version.json. 

Replace "<your system URL>" with your system's URL and "<your SAPUI5 version>" with the version of SAPUI5 you want to check (e.g. "1.90.0"). Once you navigate to this URL, the version of SAPUI5 being used will be displayed in the JSON response.


In conclusion, there are several ways to check the SAP UI5 version in SAP Fiori, including using the SAPUI5 Version Info app, the browser developer tools, and the SAPUI5 library information page. By keeping your SAP Fiori applications up-to-date with the latest SAP UI5 libraries, you can ensure that your applications are running smoothly and taking full advantage of the latest features and functionality.

Read more
Filtering SAPUI5 OData V4 Expanded Entities

Filtering SAPUI5 OData V4 Expanded Entities

Sanjo Thomas•12:07:00

One of the key features of SAPUI5 is the ability to consume OData services. OData is a protocol for creating and consuming RESTful web services. In this blog, we will explore how to filter expanded entities in OData V4 using SAPUI5.

OData V4 introduced a new feature called "expand" that allows us to retrieve related entities along with the main entity in a single request. This feature helps to reduce the number of requests required to retrieve related data and improves the performance of the application. However, sometimes we may need to filter the expanded entities based on certain conditions. Let's see how we can achieve this using SAPUI5.



First, let's consider an example where we have two entities, "Orders" and "OrderItems". Each order can have multiple order items. We want to retrieve all the orders along with their order items where the order total is greater than 1000.


To achieve this, we need to create a filter expression that applies to both the main entity and the expanded entity. Here's how we can do it in SAPUI5:


```

var oModel = new sap.ui.model.odata.v4.ODataModel({

  serviceUrl: "/path/to/service",

  synchronizationMode: "None",

  operationMode: "Server",

  groupId: "$auto",

  autoExpandSelect: true

});


var oOrdersBinding = oModel.bindList("/Orders", null, null, null, {

  $expand: "OrderItems"

});


var oFilter = new sap.ui.model.Filter("Total", "GT", 1000);


oOrdersBinding.filter(oFilter);


oOrdersBinding.attachDataReceived(function(oEvent) {

  var aOrders = oEvent.getParameter("data").results;

  

  // Loop through the orders and their order items

  aOrders.forEach(function(oOrder) {

    oOrder.OrderItems.results.forEach(function(oOrderItem) {

      // Do something with the order item

    });

  });

});

```


In the code above, we first create an OData model and bind it to the "Orders" entity set. We also set the "$expand" parameter to "OrderItems" to retrieve the related order items for each order.


Next, we create a filter expression that filters the "Total" property of both the main entity and the expanded entity. We apply this filter to the binding object using the "filter" method.


Finally, we attach a "dataReceived" event handler to the binding object to retrieve the results. We loop through the orders and their order items and perform some action with each order item.


In conclusion, filtering expanded entities in OData V4 using SAPUI5 is a powerful feature that can help improve the performance of your application. With the help of the filter expression, we can retrieve only the data we need and avoid unnecessary requests to the server.

Read more

Use strict in controller.js file

Sanjo Thomas•06:34:00

 

In this blog, we will see the use of "use strict" directive, which is new in ECMAScript version 5.

Lots of developers don’t use "use strict" to ensure their code is running in a secure way. It's important to follow best practices with your code. This article will help you do just that!

The purpose of using strict is to indicate that code should be run in strict mode. For example, an undeclared variable cannot be used in strict mode.

All modern browsers except Internet Explorer 9 and below support "use strict".

                                                             

Declaring ‘’Use strict”

Strict mode is declared by adding "use strict". Beginning of a script or function. Declared at the top of the script and has global scope (all code in the script runs in strict mode).

Example

"use strict";
myRandomFunction();

function myRandomFunction () {
  x = 
9;   // This will also cause an error because x is not declared
}

Declared inside a function, it has local scope (only the code inside the function is in strict mode):

x = 9;       // This will not cause an error.
myFunction();


function myRandomFunction() {
  
"use strict";
  y = 
10;   // This will cause an error
}

 

Why strict mode?

Strict mode makes it easy to write "safe" JavaScript.

Strict mode turns the previously accepted "bad syntax" into a real error. For example, in regular JavaScript, mistyped variable names create new global variables.

Strict mode throws an error, so you can't accidentally create a global variable. In normal JavaScript, assigning a value to a non-writable property does not give the developer an error message. In strict mode, assignment to a non-writable property, getter-only property, non-existent property, variable, or object throws an error.

 

Read more
How to import Excel CSV file to SAP UI5 Application.

How to import Excel CSV file to SAP UI5 Application.

Sanjo Thomas•06:59:00

In this blog, we will see how can we import a csv file in SAP UI5 application. 

This would be a bit different from importing excel file just as I explained inthe previous blog, since in this technique we wont be rquired to use a third party library.

Just like in my previous blog, lets keep the use case simple. We will have a simple view with a FileUploader to browse a csv file and a table to display the data.

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m" xmlns:u="sap.ui.unified" xmlns:l="sap.ui.layout.form"
	controllerName="com.fileuploader.FileUpload" xmlns:html="http://www.w3.org/1999/xhtml">
	<Page title="Demo on CSV File Upload">
	<content>
		<l:SimpleForm editable="true">
		 <l:content>
		  <Label text="File Name">
		  </Label>
		<VBox>
		 <u:FileUploader id="idfileUploader" width="50%"
		    sameFilenameAllowed="false" buttonText="" fileType="CSV"
		    placeholder="Choose a CSV file" style="Emphasized">
		</u:FileUploader>
		<Button text="Upload" press="onUpload"></Button>
		</VBox>
		</l:content>
		</l:SimpleForm>

		<Table id="idTable" items="{/}">
		<items>
		    <ColumnListItem>
			<cells>
			<Text text="{VBELN}"></Text>
			<Text text="{ERDAT}"></Text>
			<Text text="{VBTYP}"></Text>
			<Text text="{TRVOG}"></Text>
			<Text text="{AUART}"></Text>
			</cells>
		   </ColumnListItem>
                </items>
	        <columns>
			<Column>
			<Text text="Sales Document"></Text>
			</Column>
			<Column>
			<Text text="Date"></Text>
			</Column>
			<Column>
			<Text text="Type"></Text>
			</Column>
		        <Column>
			<Text text="Sales Org"></Text>
			</Column>
			<Column>
			<Text text="Category"></Text>
			</Column>
		</columns>
		</Table>
		</content>
	</Page>
</core:View>



Now update the code in the onUpload function in the respective controller.

onUpload : function(e) {
	
	var fU = this.getView().byId("idfileUploader");
	var domRef = fU.getFocusDomRef();
	var file = domRef.files[0];
	
	
	// Create a File Reader object
	var reader = new FileReader();
	var t = this;
	
	reader.onload = function(e) {
	    var strCSV = e.target.result;
	    var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
	    var noOfCols = 5;

	    // To ignore the first row which is header
	    var hdrRow = arrCSV.splice(0, noOfCols);

	    var data = [];
	    while (arrCSV.length > 0) {
		var obj = {};
		// extract remaining rows one by one
		var row = arrCSV.splice(0, noOfCols)
		for (var i = 0; i < row.length; i++) {
		    obj[hdrRow[i]] = row[i].trim()
		}
		// push row to an array
		data.push(obj)
	    }
	    
	    // Bind the data to the Table
	    var oModel = new sap.ui.model.json.JSONModel();
	    oModel.setData(data);
	    var oTable = t.byId("idTable");
	    oTable.setModel(oModel);
	};
	reader.readAsBinaryString(file);
    }

The above code in onUpload function will read the data in CSV file and load it to json model and bind it to the table.


Hereby, we have successfully uploaded the CSV to UI5 application and shown it on the table. Now, as per requirement user can select a particular record and perform CRUD operations.

This way we have seen both ways of importing Excel and CSV files to UI5 application. We can also add some additional validations on excel imported files by simply comparing the desired template with the imported file template. This we can see in the next blog.

Read more
 Custom control to make a Radar Chart using Chart.js library in SAPUI5.

Custom control to make a Radar Chart using Chart.js library in SAPUI5.

Sanjo Thomas•01:40:00
SAP UI5 framework has provided many built in libraries to make charts, like sap viz, vizframe, makit, micro charts etc. Hence, all the commonly used charts are already provided in these libraries like bar, line, column, combined, heatmap, scatter, bubble, donut, pie etc.

But there are some limitations too, as they don't support any other kind of charts like Radar charts, 3-d charts, and similarly many other charts. So in the blog, we will see how to incorporate some other chart libraries in sapui5 application.

In this example,we will use Chart.js library to make a Radar chart, with the help of a custom control in sapui5. Here, you would find the sample of Radar Chart we would be using in our application.


Lets start from scratch here, we build an application in sap web ide, and name it as RadarChart, and suppose we have a basic app structure already created.

Steps

1) Download the chart.js file from this Link, and import this file in your project directory under the folder control and name it as chart.js.

2) Now, we have to create Radar chart, hence we would make use of a custom control, which would extend the chart.js library. Hence we need to create 3 more js files, in the control folder, RadarChart.js, Dataset.js, Value.js.

I have uploaded the control folder structure onto Git hub for your convenience, download this folder into your project directory.

Your project structure would look something like this:


3) Now to make use of this newly created custom control, we use it in the Main.view.xml.
<p:RadarChart
                class="sapUiResponsiveMargin"
                scaleOverride="{/options/scaleOverride}"
                scaleStartValue="{/options/scaleStartValue}"
                scaleSteps="{/options/scaleSteps}"
                scaleStepWidth="{/options/scaleStepWidth}"
                height="600px" width="600px">
                <p:axes>
                    <core:Item text="January" />
                    <core:Item text="February" />
                    <core:Item text="March" />
                    <core:Item text="April" />
                    <core:Item text="May" />
                    <core:Item text="June" />
                    <core:Item text="July" />
                    <core:Item text="August" />
                </p:axes>
                <p:dataSets>
                    <p:DataSet fillColor="rgba(102,45,145,.1)" strokeColor="rgba(102,45,145,1)" pointColor="rgba(220,220,220,1)" pointStrokeColor="#fff" data="{/dataset1}">
                        <p:Value value="{value}" />
                    </p:DataSet>
                    <p:DataSet fillColor="rgba(63,169,245,.1)" strokeColor="rgba(63,169,245,1)" pointColor="rgba(151,187,205,1)" pointStrokeColor="#fff" data="{/dataset2}">
                        <p:Value value="{value}" />
                    </p:DataSet>
                </p:dataSets>
            </p:RadarChart>

4) Here in the above step we have made use of different axes, hence we have provided the different axes, similarly we have also provided the dateset which is being populated from a model. Hence we need to set the model somewhere, here I have set the model in the Main.controller.js.

        onInit: function() {
            this.getView().setModel(new JSONModel({
                dataset1: [
                    { value: 4 },
                    { value: 5 },
                    { value: 4 },
                    { value: 2.5 },
                    { value: 3 },
                    { value: 4 },
                    { value: 3.5 },
                    { value: 4 }
                ],
                dataset2: [
                    { value: 2 },
                    { value: 3 },
                    { value: 3 },
                    { value: 5 },
                    { value: 2 },
                    { value: 3 },
                    { value: 4 },
                    { value: 3 }
                ],
                options: {
                    scaleOverride: false,
                    scaleStartValue: 0,
                    scaleSteps: 5,
                    scaleStepWidth: 1
                }
            }));
        }
5) Now run the application, and you would be able to see the following output:



Hope you liked this blog, if you have any query regarding this, you may post your comments below, or you may personally contact me on sapui5tutors@gmail.com.
Read more