Category: UI5 Integrations

  • Download excel in SAP UI5 using XLSX JS

    Introduction

    Discover the seamless integration of ‘Download Excel in SAP UI5 using XLSX JS.’ Dive into this comprehensive guide that unveils the step-by-step process to harness the power of XLSX JS, optimizing SAP UI5 applications. Ideal for developers and SAP enthusiasts, this tutorial not only simplifies data exportation into Excel format but also boosts the functionality of your UI5 projects. Stay ahead in the evolving landscape of SAP and enhance your skills with this essential technique.

    What is XLSX/Sheet.js?

    XLSX.js is a JavaScript library that facilitates reading and writing various spreadsheet file formats, including XLSX, which is the format used by modern versions of Microsoft Excel. In essence, it allows developers to handle Excel files (both reading and creating them) directly in JavaScript, making it easier to integrate spreadsheet functionalities in web applications.

    For instance, in the context of SAP UI5 or other web frameworks, XLSX.js can be used to provide users with the ability to download data from the application in Excel format or upload Excel files for processing in the application, all without requiring server-side processing or additional software installations.

    How to Download excel in SAP UI5 using XLSX JS?

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"excelProject.excelProject": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="excelProject.excelProject" data-id="container" data-settings='{"id" : "excelProject"}'></div>
        </body>
    </html>

     

    View.XML

    <mvc:View controllerName="excelProject.excelProject.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Download Table in Excel">
                        <content>
                        <Button text="Export to Excel" press="onExportToExcel"/>
            <Table id="idProducts">
            <columns>
                <Column
                    width="12em">
                    <Text text="Name" />
                </Column>
                <Column
                    minScreenWidth="Tablet"
                    demandPopin="true">
                    <Text text="City" />
                </Column>
            </columns>
            <items>
                <ColumnListItem vAlign="Middle">
                    <cells>
                        <Text	text="Rudra" />
                        <Text	text="Mughalsarai" />
                    </cells>
                </ColumnListItem>
                <ColumnListItem vAlign="Middle">
                    <cells>
                        <Text	text="Deepak" />
                        <Text	text="Kolkata" />
                    </cells>
                </ColumnListItem>
            </items>
                </Table>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.Js

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("excelProject.excelProject.controller.Main", {
            onInit: function () {
    
            },
    
            onExportToExcel: function () {
                // Get the JSON data
                var rows = [];
            var selection = this.getView().byId('idProducts').getSelectedItems();
            selection.forEach(val => {
            var data = val.getBindingContext().getObject();
            rows.push(data);
            });
    
                // Convert JSON to Excel workbook
                var workbook = XLSX.utils.book_new();
                var worksheet = XLSX.utils.json_to_sheet(rows);
                XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    
                // Save the workbook as an Excel file
                XLSX.writeFile(workbook, "data.xlsx");
            }
    
        });
    });

     

    Output

    Download excel in SAP UI5 using XLSX JS

  • Developing Analytic Map using SAP UI5

    Introduction

    Discover the world of data visualization in an engaging and interactive way with our comprehensive guide on “Developing Analytic Map using SAP UI5”. Explore how to harness the power of SAP UI5, a highly efficient JavaScript framework, to create visually striking and informative analytic maps that transform raw data into meaningful insights.

    In this article, we delve into the step-by-step process of creating analytic maps, providing clear instructions and expert tips to help you effectively illustrate complex data sets. Whether you’re monitoring logistics, tracking global sales, or studying demographic trends, analytic maps present data in a geographic context, allowing for a more intuitive understanding and smarter decision-making process.

    Unlock the potential of geo-spatial data visualization and learn how to create dynamic, interactive maps with SAP UI5. This guide is perfect for developers seeking to enhance their skills, as well as businesses striving for a data-driven approach to achieve their goals. Let’s chart your path to successful data visualization.

    What is an Analytic Map?

    An Analytic Map is a type of data visualization that combines geographical data with quantitative data to provide insights in a visually compelling way. The primary goal of analytic maps is to help interpret and analyze patterns, trends, and correlations in data that may otherwise go unnoticed in a standard table or chart.

    In an analytic map, data is typically represented through various colors, symbols, or sizes of specific regions or points on the map. For instance, in a global sales report, the sales volume for each country can be represented by different colors, with darker shades indicating higher sales.

    These maps can be interactive, allowing users to zoom in and out, hover over specific regions to get more details, and even click on parts of the map to navigate to other reports or sections of the data.

    Analytic maps are particularly useful in a wide range of fields including business intelligence, public health, environmental studies, transportation planning, and many more. They help in understanding spatial relationships and geographic patterns in data, thereby aiding in more informed decision-making.

    Uses of Analytic Map in SAP UI5

    Analytic Maps in SAP UI5 open up a whole world of possibilities when it comes to data visualization and analysis. They can be used in various ways to provide spatial context to data, and deliver insights in an engaging and interactive way. Here are some of the primary uses:

    1. **Geospatial Data Visualization**: With SAP UI5, you can present your data in a geographical context, such as sales performance across different regions or tracking shipments in real-time.

    2. **Business Intelligence**: Analytic maps are a powerful tool in business intelligence, allowing businesses to visually compare data across different locations, track changes over time, and identify patterns and trends.

    3. **Interactive User Experience**: SAP UI5 analytic maps are interactive, enabling users to zoom in and out, hover over regions to get more details, and click on map points to navigate to other reports or sections of the data. This enriches the user experience, making data exploration more intuitive and engaging.

    4. **Real-Time Tracking**: For industries that rely on real-time location data, such as logistics, transportation, and supply chain management, SAP UI5 analytic maps can provide live updates and visual tracking.

    5. **Customization**: SAP UI5 provides the flexibility to customize the appearance and functionality of your maps according to your specific requirements. You can alter colors, shapes, sizes, and labels to best represent your data.

    6. **Integration with SAP Systems**: Given that SAP UI5 is a part of the larger SAP ecosystem, analytic maps can easily be integrated with other SAP applications and tools, allowing for seamless data flow and advanced analytics.

    Remember, the key to successfully leveraging analytic maps lies in understanding your data and knowing what story you want to tell. With SAP UI5, you’re equipped with a powerful tool that can transform your data into meaningful, actionable insights.

    Developing Analytic Map using SAP UI5

    View

    <mvc:View controllerName="geoMap.geoMap.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns:l="sap.ui.layout" displayBlock="true"
        xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="{i18n>title}">
                        <content>
                            <l:VerticalLayout id="mapContainer" width="100%"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/vbm/AnalyticMap",
        "sap/ui/vbm/Spot",
    ], function (Controller, AnalyticMap, Spot) {
        "use strict";
    
        return Controller.extend("geoMap.geoMap.controller.Main", {
            onInit: function () {
                var oMapView = new AnalyticMap({
                    width: "100%"
                });
                this.getView().byId("mapContainer").addContent(oMapView);
                var oSpot = new Spot({
                    "position": "77.1024902;28.7040592;0", // Replace with actual coordinates
                    "tooltip": "Delhi",
                    "type": "Success",
                    "text": "Delhi"
                });
    
                var oSpot2 = new Spot({
                    "position": "-74.013327;40.705395;0", // Replace with actual coordinates
                    "tooltip": "New York",
                    "type": "Inactive",
                    "text": "New York"
                });
    
                var oSpots = new sap.ui.vbm.Spots({
                    items: [oSpot, oSpot2]
                });
    
                oMapView.addVo(oSpots);
    
            }
        });
    });

     

    Output

    Developing Analytic Map using SAP UI5

  • Convert PDF to Text in SAP UI5 using PDF.js

    Introduction

    Discover the power of PDF.js in our comprehensive guide to transforming PDF files into readable text within the SAP UI5 framework. As digital data continues to proliferate, the need for seamless data conversion and extraction increases. Leveraging the power of PDF.js, we will unravel the process of converting complex PDF files into simple text directly in your SAP UI5 applications. This powerful JavaScript library brings PDF rendering capabilities to your browser, making it easier than ever to parse and extract data from PDF files.

    Whether you’re a seasoned SAP UI5 developer or just beginning your journey, this guide offers a practical, step-by-step process for implementing PDF.js in your applications. From installation to implementation, we’ve got you covered. Improve your SAP UI5 skill set, enhance your applications, and unlock new possibilities with PDF.js today. Let’s dive into the world of PDF to text conversion in SAP UI5 with PDF.js.

    What is PDF.js

    PDF.js is a robust, open-source JavaScript library developed by Mozilla. It is used to parse and render PDF files directly in a web browser. One of its primary features is its ability to maintain the high fidelity of the original PDF file, including its fonts, vector graphics, and images.

    CDN for PDF.js: cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js

    The library offers a wide range of functionalities. For instance, it allows developers to highlight text within the PDF, search for specific text, and zoom in or out of the document. PDF.js can also be used to convert PDF files into other formats such as text or images, which is especially useful when you need to extract or manipulate the content of PDF files programmatically.

    By leveraging the power of modern web standards like HTML5 and JavaScript, PDF.js ensures a seamless, platform-independent solution that works across various devices and operating systems. As a result, it’s used in numerous applications and projects around the world, including the Firefox browser, where it’s used as the default PDF viewer.

    How to convert PDF to Text using PDF.js using JavaScript

    To convert PDF to Text using PDF.js with JavaScript, you can follow these steps:

    1. First, you need to include the PDF.js library in your project. You can download it from the official GitHub repository and include it in your HTML file.

    2. Load your PDF file using the ‘getDocument’ function. This function returns a promise that is resolved with a PDFDocumentProxy object.

    3. Once you have the PDFDocumentProxy object, you can call the ‘getPage’ function to get a particular page (let’s assume the first page). This function also returns a promise that is resolved with a PDFPageProxy object.

    4. Now, you can call the ‘getTextContent’ function on the PDFPageProxy object. This function returns a promise that is resolved with a TextContent object.

    5. The TextContent object has an array called ‘items’ which contains the individual text items of the page. You can loop through this array and concatenate all the strings to get the full text of the page.

    6. Repeat steps 3 to 5 for all pages in the PDF document.

    Please note that these are the general steps. Depending on your specific project and setup, there might be some variations in how you apply them. You will need to have a good understanding of JavaScript and Promises to work with PDF.js effectively.

    Also note that text extraction with PDF.js might not always be perfect. Due to the way PDF files are structured, sometimes the order of the text can get mixed up, or some characters might not get extracted correctly.

    Convert PDF to Text in SAP UI5 using PDF.js

    Index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"pdfUploader.pdfUploader": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="pdfUploader.pdfUploader" data-id="container" data-settings='{"id" : "pdfUploader"}'></div>
        </body>
    </html>

    View

    <mvc:View controllerName="pdfUploader.pdfUploader.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns:u="sap.ui.unified" displayBlock="true"
        xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Convert PDF to Text in SAP UI5 using PDF.js">
                        <content>
                            <VBox alignItems="Center" justifyContent="Center">
                                <u:FileUploader name="pdfUploader" buttonText="Upload PDF" fileType="pdf" change="onFileUpload"/>
                                <TextArea id="textArea" rows="10" width="100%" editable="false"/>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("pdfUploader.pdfUploader.controller.Main", {
            onInit: function () {
    
            },
    
            onFileUpload: function (event) {
                var that = this;
                var file = event.getParameter("files")[0];
                var reader = new FileReader();
    
                reader.onload = function (event) {
                    var pdfData = new Uint8Array(event.target.result);
    
                    // Load the PDF data using PDF.js
                    pdfjsLib.getDocument(pdfData).promise.then(function (pdf) {
                        // Access the first page of the PDF
                        pdf.getPage(1).then(function (page) {
                            // Extract the text content from the page
                            page.getTextContent().then(function (textContent) {
                                var extractedText = "";
    
                                // Concatenate the text content from all items
                                textContent.items.forEach(function (item) {
                                    extractedText += item.str + " ";
                                });
    
                                // Bind the extracted text to the TextArea control
                                var textArea = that.getView().byId("textArea");
                                textArea.setValue(extractedText);
                            }.bind(this));
                        });
                    });
                }.bind(this);
    
                reader.readAsArrayBuffer(file);
            },
        });
    });

     

    Output

    Sample PDF:

    Sample PDF

    After Upload:

    Convert PDF to Text in SAP UI5 using PDF.js

     

  • Convert Excel data to JSON Data in SAP UI5

    Introduction

    Welcome to our comprehensive guide on ‘Converting Excel Data to JSON Data in SAP UI5.’ This practical approach simplifies the way we manage and interpret large Excel data sets, translating them into compact, easy-to-handle JSON files within the SAP UI5 framework. With this strategy, we aim to improve your data integration processes and quicken application development, allowing for more efficient and streamlined operations. We will learn how to Upload an excel file and convert it into JSON and bind it to the table or any other component.

    Excel to JSON in JavaScript

    Converting Excel data to JSON format in JavaScript typically involves parsing the Excel file, reading its data, and then transforming it into JSON format. Here is a simple step-by-step process using the ‘xlsx’ library, a popular JavaScript library to read, write and parse various spreadsheet formats.

    1. Create an HTML input element of type ‘file’ that accepts Excel files, allowing the user to select an Excel file from their device.

    2. Use the FileReader API to read the content of the selected file. The FileReader API is part of the web API and allows you to read file content in JavaScript.

    3. Use a library like `xlsx` to parse the Excel data. The parsing process converts the raw file data into a format that the library can work with.

    4. Extract a specific worksheet from the workbook. If you’re unsure, you can simply extract the first sheet.

    5. Use a function provided by the `xlsx` library to convert the worksheet data into JSON format.

    6. At this point, the Excel data has been converted into an array of JavaScript objects (JSON format). You can now use this data in your application.

    xlsx.js library

    The xlsx.js library is a robust and comprehensive JavaScript library that is designed to simplify the process of parsing and manipulating Excel files within the browser and Node.js. The library provides the capability to read and write various spreadsheet formats such as XLSX, XLSM, XLSB, and ODS.

    Convert Excel data to JSON Data in SAP UI5

    Index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"exceltoJson.exceltoJson": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="exceltoJson.exceltoJson" data-id="container" data-settings='{"id" : "exceltoJson"}'></div>
        </body>
    </html>

     

    View

    <mvc:View controllerName="exceltoJson.exceltoJson.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:u="sap.ui.unified">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Converting Excel data to JSON Data in UI5">
                        <content>
                            <u:FileUploader id="fileUploader" change="onFileUpload"/>
                            <TextArea id="textArea" rows="10" width="100%" editable="false"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("exceltoJson.exceltoJson.controller.Main", {
            onInit: function () {
    
            },
    
            onFileUpload: function (event) {
                var that = this;
                var file = event.getParameter("files")[0];
                var reader = new FileReader();
    
                reader.onload = function (e) {
                    var data = new Uint8Array(e.target.result);
                    var workbook = XLSX.read(data, {
                        type: 'array'
                    });
    
                    // Extract data from the first sheet
                    var worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    var jsonData = XLSX.utils.sheet_to_json(worksheet);
    
                    // Use the jsonData as desired (e.g., display in a table, perform operations, etc.)
                    console.log(jsonData);
                    that.byId("textArea").setValue(JSON.stringify(jsonData));
                };
    
                reader.readAsArrayBuffer(file);
            }
    
        });
    });

     

    Input

    Output

  • Convert a JSON to Excel in SAP UI5

    Introduction

    Looking to seamlessly convert JSON data to Excel format within your SAP UI5 application? Look no further! In this comprehensive guide, we’ll walk you through a step-by-step process to effortlessly convert JSON data to Excel spreadsheets using SAP UI5. This powerful integration allows you to efficiently export and share your data in a user-friendly Excel format, enabling better data analysis and collaboration across your organization. Follow along to unlock the full potential of your SAP UI5 application by mastering the art of JSON to Excel conversion. Let’s dive in and learn How can we export JSON data to EXCEL in SAPUI5.

    JSON to Excel in JavaScript

    JSON (JavaScript Object Notation) is a lightweight data-interchange format that is widely used for storing and exchanging data. It is easy for humans to read and write, and also easy for machines to parse and generate. On the other hand, Excel is a popular spreadsheet program that allows users to store, organize, and analyze data in a tabular format.

    Converting JSON to Excel in JavaScript involves the process of transforming JSON data into a format compatible with Excel. This transformation is typically done using JavaScript libraries or functions that facilitate data manipulation and export capabilities.

    The steps involved in the JSON to Excel conversion process using JavaScript are as follows:

    1. Parsing JSON Data: The first step is to parse the JSON data and convert it into a JavaScript object, which allows for easy access and manipulation of the data.

    2. Creating Excel-Compatible Data: Next, JavaScript functions or libraries are used to structure the JSON data into a format that can be interpreted by Excel. This may involve converting the JSON object into an array of arrays or other Excel-friendly data structures.

    3. Generating Excel File: Once the data is prepared in a compatible format, JavaScript can be used to generate an Excel file. This process involves creating the appropriate Excel file format, populating it with the converted JSON data, and configuring any necessary settings, such as cell formatting and sheet names.

    4. Download or Display: Finally, the generated Excel file can be made available to the user for download or displayed directly within the web application, depending on the desired functionality.

    By leveraging the power of JavaScript and its libraries, developers can seamlessly convert JSON data to Excel format, enabling efficient data handling and analysis in Excel spreadsheets. This capability is valuable for web applications that need to export data for reporting, sharing, or further analysis in the familiar Excel environment.

    xlsx.js library

    xlsx.js is a powerful JavaScript library that enables seamless manipulation and generation of Microsoft Excel files (XLSX format) directly within web applications. With xlsx.js, developers can create, read, modify, and export Excel spreadsheets using pure JavaScript code, eliminating the need for server-side processing or browser plugins.

    Convert a JSON to Excel in SAP UI5

    Index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"excelProject.excelProject": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="excelProject.excelProject" data-id="container" data-settings='{"id" : "excelProject"}'></div>
        </body>
    </html>

     

    View

    <mvc:View controllerName="excelProject.excelProject.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Convert a JSON to Excel in UI5">
                        <content>
                            <Button text="Export to Excel" press="onExportToExcel"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("excelProject.excelProject.controller.Main", {
            onInit: function () {
    
            },
    
            onExportToExcel: function () {
                // Get the JSON data
                var jsonData = [{
                    Name: "John",
                    Age: 25,
                    City: "New York"
                }, {
                    Name: "Alice",
                    Age: 30,
                    City: "London"
                }, {
                    Name: "Bob",
                    Age: 35,
                    City: "Paris"
                }];
    
                // Convert JSON to Excel workbook
                var workbook = XLSX.utils.book_new();
                var worksheet = XLSX.utils.json_to_sheet(jsonData);
                XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    
                // Save the workbook as an Excel file
                XLSX.writeFile(workbook, "data.xlsx");
            }
    
        });
    });

     

    Output

    Convert a JSON to Excel in SAP UI5

  • Custom Message Popover Integration in SAP UI5

    Introduction

    In this tutorial, we will learn simple steps to implement Custom Message Popover Integration in SAP UI5.

    In SAP UI5, the ability to display informative messages or notifications to users is crucial for enhancing user experience and providing important feedback. Custom Message Popover integration in SAP UI5 allows developers to create and display tailored messages in a visually appealing and interactive manner. By leveraging this feature, developers can effectively communicate messages, warnings, errors, or any other relevant information to users within their applications.

    Custom Message Popover integration in SAP UI5 involves utilizing the sap.m.Popover control to create a popover-like dialog that can be triggered programmatically. This popover can be customized to display messages with different severity levels, such as success, information, warning, or error. Developers have full control over the content, styling, and behavior of the popover, enabling them to design a highly interactive and visually consistent messaging experience.

    In this project, we will explore the process of integrating Custom Message Popover in SAP UI5 applications. We will learn how to define and customize the popover control, define messages with different severity levels, and dynamically populate the popover with relevant content. Additionally, we will explore how to handle user interactions with the popover, such as dismissals or further actions based on the displayed messages.

    By the end of this project, you will have a solid understanding of how to integrate Custom Message Popover in SAP UI5 and leverage its capabilities to deliver informative and visually appealing messages to users. This integration will enhance the usability of your applications and empower users with timely and actionable information, contributing to a more seamless and efficient user experience. So, let’s dive into the world of Custom Message Popover integration in SAP UI5 and unlock the potential to elevate your application’s messaging capabilities.

    What is Message Popover in SAP UI5

    In SAP UI5, a Message Popover is a UI control that provides a convenient and visually appealing way to display messages, notifications, or alerts to users within an application. It serves as a container for displaying multiple messages of different severity levels, such as success, information, warning, or error.

    The Message Popover control in SAP UI5, typically represented as a small dialog or popover-like element, offers a centralized location for presenting important information to users without disrupting their workflow. It allows developers to communicate various types of messages in a concise and organized manner, improving the overall user experience and facilitating effective communication.

    The Message Popover in SAP UI5 provides the following key features:

    1. Message Types and Severity Levels: The Message Popover supports different message types with associated severity levels, enabling developers to categorize and differentiate messages based on their importance or urgency.

    2. Message Aggregation: The Message Popover can aggregate multiple messages, allowing developers to display multiple notifications or alerts simultaneously. Messages can be added or removed dynamically based on application logic or user interactions.

    3. Styling and Formatting: Developers can customize the appearance and styling of the Message Popover to match the overall design language and branding of their application. This includes options to define the layout, colors, icons, and other visual elements.

    4. Interaction and Actionability: Users can interact with messages within the Message Popover by performing actions associated with each message. This can include dismissing a message, acknowledging it, or triggering further actions based on the message content.

    5. Localization and Accessibility: The Message Popover supports localization, allowing developers to display messages in different languages or adapt to regional preferences. It also ensures compliance with accessibility guidelines, making the messages accessible to users with disabilities.

    By leveraging the Message Popover control in SAP UI5, developers can effectively communicate important information, warnings, errors, or any other relevant messages to users in a user-friendly and organized manner. This enhances the usability and user experience of the application by providing timely and actionable feedback.

    Steps for Custom Message Popover Integration in SAP UI5

    Here are the steps for integrating a Custom Message Popover in SAP UI5:

    1. Set up the SAP UI5 Development Environment:
    – Install SAPUI5 library and necessary development tools.
    – Create a new SAP UI5 project or use an existing project as a base.

    2. Define the UI Layout:
    – Create a view or a page where the Message Popover will be displayed.
    – Design the overall layout using SAP UI5 controls like panels, containers, or grids.

    3. Create the Message Popover Control:
    – Instantiate the sap.m.Popover control in your view or page.
    – Configure the popover with desired properties such as width, height, and positioning.

    4. Define Message Models and Data Binding:
    – Define a message model to store the messages to be displayed in the popover.
    – Populate the message model with the relevant messages based on your application logic.
    – Bind the message model to the Message Popover control to dynamically display the messages.

    5. Customize the Message Popover Content:
    – Define the content of the Message Popover control, including the layout and formatting of the messages.
    – Utilize UI5 controls like sap.m.MessageStrip or sap.m.List to display individual messages within the popover.
    – Customize the appearance of the messages based on their severity levels using icons, colors, or formatting.

    6. Handle User Interactions:
    – Implement event handlers or listeners for user interactions with the messages, such as dismissals or further actions.
    – Define appropriate actions based on the user’s response to a message, like acknowledging or resolving the issue.

    7. Displaying the Message Popover:
    – Trigger the display of the Message Popover control based on specific events or application logic.
    – Set the popover’s position relative to a target control or a specific location on the screen.
    – Show or hide the Message Popover dynamically as needed.

    8. Test and Refine:
    – Test the integration of the Custom Message Popover by simulating various scenarios and verifying the display and behavior of messages.
    – Gather feedback from users and iterate on the design and functionality based on their requirements and suggestions.
    – Continuously refine and optimize the Custom Message Popover’s performance, styling, and user experience.

    By following these steps, you can successfully integrate a Custom Message Popover in your SAP UI5 application. This integration will enable you to display informative messages and notifications to users in a visually appealing and interactive manner, enhancing the usability and overall user experience of your application.

    View Code

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" height="100%"
        displayBlock="true">
        <Page>
            <customHeader>
                <Bar>
                    <contentLeft>
                        <Button id="msgpop1" icon="sap-icon://message-popup" text="{popoverModel>/messagesLength}" type="{popoverModel>/type}"
                            press="handleMessagePopoverPress"/>
                    </contentLeft>
                    <contentMiddle>
                        <Title text="My Project Ideas: Message Popover Integration in SAP UI5" titleStyle="H2"></Title>
                    </contentMiddle>
                    <contentRight>
                        <Button text="Get Success Message" press="onSuccess" icon="sap-icon://message-success"/>
                        <Button text="Get Error Message" press="onError" icon="sap-icon://message-error"/>
                    </contentRight>
                </Bar>
            </customHeader>
        </Page>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device",
        'sap/m/MessagePopover',
        'sap/m/MessagePopoverItem'
    ], function (Controller, MessageBox, MessageToast, JSONModel, Device, MessagePopover, MessagePopoverItem) {
        "use strict";
    
        var oMessageTemplate = new MessagePopoverItem({
            type: '{T}',
            title: '{S}',
        });
    
        var oMessagePopover = new MessagePopover({
            items: {
                path: '/',
                template: oMessageTemplate
            }
        });
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                var that = this;
                var pop_msgModel = new sap.ui.model.json.JSONModel({
                    "messagesLength": "",
                    "type": "Default"
                });
                this.getView().setModel(pop_msgModel, "popoverModel");
                var popModel = new sap.ui.model.json.JSONModel({});
                oMessagePopover.setModel(popModel);
            },
    
            onSuccess: function () {
                var that = this;
                var message = "This is a success message!";
                var w_data = [];
                w_data.push({
                    T: "Success",
                    S: message
                });
                var previous = oMessagePopover.getModel().getData();
                if (previous.length === undefined)
                    previous = [];
                var updated = previous !== "" ? previous.concat(w_data) : w_data
                oMessagePopover.getModel().setData(updated);
                oMessagePopover.getModel().refresh(true);
                that.getView().getModel("popoverModel").getData().messagesLength = updated.length;
                that.getView().getModel("popoverModel").getData().type = "Emphasized";
                that.getView().getModel("popoverModel").refresh(true);
            },
    
            onError: function () {
                var that = this;
                var message = "This is an error message!";
                var w_data = [];
                w_data.push({
                    T: "Error",
                    S: message
                });
                var previous = oMessagePopover.getModel().getData();
                if (previous.length === undefined)
                    previous = [];
                var updated = previous !== "" ? previous.concat(w_data) : w_data
                oMessagePopover.getModel().setData(updated);
                oMessagePopover.getModel().refresh(true);
                that.getView().getModel("popoverModel").getData().messagesLength = updated.length;
                that.getView().getModel("popoverModel").getData().type = "Emphasized";
                that.getView().getModel("popoverModel").refresh(true);
            },
    
            handleMessagePopoverPress: function (oEvent) {
                oMessagePopover.toggle(oEvent.getSource());
            }
        });
    });

     

    Output

    Custom Message Popover Integration in SAP UI5

  • Design a Code Editor using SAP UI5

    Introduction

    In this tutorial, we will learn how to design a simple code editor using SAP UI5. These code editors can be used to run, pretty printer and test codes. SAP UI5 provides different types of code editors like javascript, ABAP, etc.

    In the world of software development, a well-designed code editor is an essential tool for programmers to write, edit, and debug their code efficiently. SAP UI5, a robust framework developed by SAP, provides a powerful and flexible solution for creating code editors with its sap.ui.codeeditor library.

    Designing a code editor using SAP UI5’s sap.ui.codeeditor involves leveraging the extensive capabilities of this library to create a user-friendly interface and enhance the overall coding experience. This powerful UI5 library offers a variety of features and functionalities, including syntax highlighting, code completion, line numbering, and more, enabling developers to streamline their coding tasks.

    In this project, we will explore the process of designing a code editor using SAP UI5’s sap.ui.codeeditor. We will delve into the key components and concepts of the sap.ui.codeeditor library and learn how to integrate them seamlessly into a user interface. By the end of this project, you will have a solid understanding of how to leverage SAP UI5 to build a code editor that caters to the needs of developers and empowers them to write clean, efficient, and error-free code.

    So, let’s embark on this journey of designing a code editor using SAP UI5’s sap.ui.codeeditor and unlock the potential to create a top-notch coding environment for programmers.

    Types of Code Editors in SAP UI5

    In SAP UI5, you have two types of code editors:

    1. Default Autocompletion:

    The Default Autocompletion feature in SAP UI5 code editors saves developers time by reducing the need to manually type long names or search for the correct syntax. It enhances productivity and accuracy by offering intelligent suggestions, thus minimizing the chance of typographical errors or misspelled identifiers. By providing real-time assistance, this autocompletion feature enables developers to write code more efficiently and maintain a consistent coding style.

    The Default Autocompletion feature in SAP UI5 code editors provides built-in support for suggesting code completions as you type. This feature leverages the code editor’s understanding of the programming language’s syntax and context to offer relevant suggestions. When enabled, the code editor analyzes the code you’re writing and provides a list of available completions for functions, variables, classes, methods, and more.

    2. Custom Autocompletion:

    In addition to the Default Autocompletion feature, SAP UI5 code editors also allow developers to define their own custom autocompletion rules. This enables them to extend the autocompletion functionality and tailor it to their specific requirements or domain-specific languages.

    With Custom Autocompletion, developers can define their own sets of suggestions for commonly used code snippets, libraries, frameworks, or any other custom context-specific completions. These custom autocompletion rules can be defined based on predefined trigger characters or specific events, such as pressing a hotkey or invoking a code generation action.

    Custom Autocompletion empowers developers to create personalized coding experiences and streamline repetitive tasks. It allows for the integration of project-specific or industry-specific code snippets, abbreviations, or templates, making it easier to write code and adhere to coding standards or best practices.

    By leveraging both the Default Autocompletion and Custom Autocompletion features in SAP UI5 code editors, developers can benefit from intelligent suggestions, improved coding speed, reduced errors, and a more tailored coding experience, ultimately enhancing their productivity and efficiency in software development.

    How to Design a Code Editor using SAP UI5

    Designing a code editor using SAP UI5 involves creating a user-friendly interface and integrating the sap.ui.codeeditor library to provide essential code editing functionalities. Here is a step-by-step guide to designing a code editor using SAP UI5:

    1. Set up the SAP UI5 Development Environment:
    – Install SAPUI5 library and necessary development tools.
    – Create a new SAP UI5 project or use an existing project as a base.

    2. Define the UI Layout:
    – Create a view or a page to hold the code editor component.
    – Design the overall layout using SAP UI5 controls like panels, containers, or grids.
    – Set up the necessary structure for the code editor and other supporting components.

    3. Integrate the Code Editor Component:
    – Include the sap.ui.codeeditor library in your project dependencies.
    – Instantiate the sap.ui.codeeditor.CodeEditor control in your view or page.
    – Configure the code editor with desired properties like height, width, syntax highlighting, and initial code content.

    4. Implement Code Editor Functionalities:
    – Enable basic code editing functionalities such as text selection, cursor navigation, and text manipulation (insertion, deletion).
    – Implement syntax highlighting by defining syntax rules for different programming languages.
    – Enable code formatting options to automatically format the code based on predefined rules.
    – Implement code validation and error highlighting by integrating with relevant parsers or linters.
    – Implement code completion feature to provide intelligent suggestions for code elements.
    – Add support for keyboard shortcuts and hotkeys to enhance the coding experience.

    5. Enhance the User Experience:
    – Implement line numbering and gutter indicators to improve code readability.
    – Add search and replace functionality to enable text search and replace operations within the code.
    – Integrate version control system functionalities like Git integration for code versioning and history tracking.
    – Provide options to customize the editor’s theme or visual appearance.
    – Implement code folding feature to allow collapsing and expanding sections of code for better organization.

    6. Handle User Interactions:
    – Implement event handlers to capture user interactions such as code changes, cursor movements, or code selection.
    – Define appropriate callbacks or event listeners to respond to user actions and trigger corresponding actions or updates.

    7. Test and Refine:
    – Test the code editor with sample code snippets to ensure proper functionality and responsiveness.
    – Gather feedback from users and iterate on the design based on their requirements and suggestions.
    – Continuously refine and optimize the code editor’s performance and user experience.

    By following these steps, you can design a code editor using SAP UI5 that provides a feature-rich and intuitive coding environment for developers. Remember to leverage the capabilities of the sap.ui.codeeditor library and tailor the editor’s functionalities to suit your specific development needs.

    View Code

    <mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout"
        xmlns:CodeEditor="sap.ui.codeeditor" height="100%" displayBlock="true">
        <Page title="My Project Ideas: Code Editor">
            <content></content>
        </Page>
        <IconTabHeader id="iconTabHeader" selectedKey="invalidKey" select=".onSelectTab">
            <items>
                <IconTabFilter text="Default Autocompletion" key="A"/>
                <IconTabFilter text="Custom Autocompletion" key="B"/>
            </items>
        </IconTabHeader>
        <CodeEditor:CodeEditor id="aCodeEditor" height="300px" type="javascript"/>
        <Button text="Pretty Printer" press="onPrettyCode"/>
        <Button text="Run JavaScript Code" press="onRunCode"/>
    </mvc:View>

     

    Controller Code

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox",
        "sap/m/MessageToast",
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device",
        "sap/ui/codeeditor/CodeEditor",
    ], function (Controller, MessageBox, MessageToast, JSONModel, Device, CodeEditor) {
        "use strict";
        var oEditor;
        var example1 = "function loadDoc() {\n\treturn 'Default Autocompletion: Write JavaScript Here';\n}";
        var example2 = "function myFunction(p1, p2) {\n\treturn 'Custom Autocompletion: Write ABAP Here';\n}";
    
        return Controller.extend("Test.Test.controller.Main", {
            onInit: function () {
                oEditor = this.byId("aCodeEditor");
                oEditor.setValue("// select tabs to see value of CodeEditor changing");
            },
    
            onSelectTab: function (oEvent) {
                var sFilterId = oEvent.getParameter("selectedKey");
                switch (sFilterId) {
                case "A":
                    oEditor.setValue(example1);
                    oEditor.setType("javascript");
                    break;
                case "B":
                    oEditor.setValue(example2);
                    oEditor.setType("abap");
                    oEditor.addCustomCompleter({
                        getCompletions: function (callback, context) {
                            // callback is provided to us by ACE so we can execute it as shown
                            // below to display suggestions to the user
                            // ideally, the array argument, provided to the following method call
                            // will be dynamically generated based on the content of the context object
                            // let's assume the context contains an sPrefix equal to 'read', which
                            // means the cursor in ACE is at the end of a 'read' word
                            // by executing the following call, we can show a list of suggestions
                            // such as: readFile, readStream, readResponse
                            callback(null, [{
                                value: "readFile()",
                                score: 100,
                                meta: "rhyme"
                            }, {
                                value: "readStream(input)",
                                score: 1,
                                meta: "params: input"
                            }, {
                                value: "readNow",
                                score: 1,
                                meta: "params: input"
                            }, {
                                value: "readStream(input, encoding)",
                                score: 1,
                                meta: "params: input, encoding"
                            }, {
                                value: "rudra(input, encoding)",
                                score: 1,
                                meta: "params: input, encoding"
                            }, {
                                value: "My Project Ideas(input, encoding)",
                                score: 1,
                                meta: "params: input, encoding"
                            }]);
                        }
    
                    });
                    break;
                default:
                    oEditor.setValue();
                    break;
                }
            },
    
            onPrettyCode: function () {
                oEditor.prettyPrint();
            },
    
            onRunCode: function () {
                var code = oEditor.getValue();
                try {
                    // Use eval to execute the code
                    eval(code);
                } catch (error) {
                    // Display any error that occurred during execution
                    alert("Code Running Failed");
                }
            }
        });
    });

     

    Output

    Output of Code Editor
    Output of Code Editor

     

    Custom Autocompletion in Code Editor
    Custom Autocompletion in Code Editor
  • Media Upload and Download using SAP UI5 and Google Firebase Storage

    Introduction

    Welcome to the ultimate guide on performing media upload and download operations using SAP UI5 and Google Firebase Storage! If you’re looking to empower your SAP UI5 application with the ability to handle media files seamlessly, you’ve come to the right place.

    In this comprehensive tutorial, we will walk you through the step-by-step process of integrating SAP UI5, a powerful JavaScript framework for building web applications, with Google Firebase Storage, a scalable and secure cloud storage solution. By combining these technologies, you’ll be able to implement robust media upload and download functionality in your SAP UI5 application.

    Throughout this tutorial, we will cover all aspects of media handling using SAP UI5 and Google Firebase Storage. We’ll guide you through the setup process, including creating a Firebase project and enabling Firebase Storage for your application.

    Next, we’ll delve into the implementation of media upload functionality. You’ll learn how to create a user interface in your SAP UI5 application where users can select and upload media files. We’ll guide you through the process of configuring Firebase Storage rules and utilizing the Firebase Storage SDK to securely upload media files to the cloud.

    After that, we’ll explore the media download process. You’ll discover how to retrieve and display media files from Firebase Storage in your SAP UI5 application. We’ll cover techniques for efficiently managing and organizing media files, allowing users to easily access and download them as needed.

    Additionally, we’ll address advanced features such as handling file metadata, implementing file filtering, and supporting various file formats. You’ll learn how to enhance the user experience by incorporating progress indicators, error handling, and file management functionalities.

    By the end of this tutorial, you’ll have a solid understanding of how to perform media upload and download operations using SAP UI5 and Google Firebase Storage. You’ll be able to seamlessly integrate media handling capabilities into your SAP UI5 application, empowering your users to efficiently manage and access media files.

    So, whether you’re a seasoned SAP UI5 developer or new to web application development, this tutorial is designed to equip you with the knowledge and skills needed to implement media upload and download functionality effectively. Get ready to take your SAP UI5 application to the next level by unlocking the power of media handling with SAP UI5 and Google Firebase Storage!

    Steps to perform Media Upload and Download using SAP UI5 and Google Firebase Storage

    Sure! Here are the steps to perform media upload and download operations using SAP UI5 and Google Firebase Storage:

    1. Set up your SAP UI5 project: Create a new SAP UI5 project or use an existing one. Set up the necessary project structure and dependencies.

    2. Set up Google Firebase: Go to the Firebase console (https://console.firebase.google.com/) and create a new project or use an existing one. Enable Firebase Storage for your project.

    3. Configure Firebase Storage: In the Firebase console, navigate to the Storage section and set up the necessary rules and permissions for your storage buckets. Define the access rules to ensure the security and privacy of your media files.

    4. Connect SAP UI5 with Google Firebase: In your SAP UI5 project, create a new JavaScript file (e.g., “firebase.js”) to handle the connection between SAP UI5 and Google Firebase. Import the necessary Firebase libraries and initialize Firebase with your project’s configuration.

    5. Implement Media Upload: Create a user interface in your SAP UI5 app that allows users to select media files for upload. Implement the logic to capture the selected file(s) and use the Firebase Storage API to upload the media files to Firebase Storage.

    6. Display Uploaded Media: Create a user interface to display the uploaded media files. Retrieve the list of uploaded files from Firebase Storage using the Firebase Storage API and bind them to SAP UI5 controls for display.

    7. Implement Media Download: Create a user interface to enable users to download media files. Implement the logic to download the selected media file(s) from Firebase Storage using the Firebase Storage API.

    8. Advanced Features: Consider implementing additional features such as file metadata management, file filtering, and supporting various file formats. Enhance the user experience by incorporating progress indicators, error handling, and file management functionalities.

    9. Update Storage Rules: To allow the upload and download functionality, you need to update storage rules. For our case, we have removed all the conditions. You can read more about it here.

    Update Storage Rules

    10. Test and Refine: Thoroughly test your media upload and download operations to ensure they are working correctly. Verify that media files can be uploaded, displayed, and downloaded properly. Handle any error scenarios gracefully and provide appropriate feedback to the user.

    By following these steps, you’ll be able to perform media upload and download operations using SAP UI5 and Google Firebase Storage. Remember to consult the documentation for SAP UI5 and Google Firebase Storage for more detailed instructions and best practices. Happy coding!

    UI5 Code to perform Media Upload and Download using Google Firebase Storage

    Main.view.xml

    <mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"
        controllerName="firebaseApp.firebaseApp.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml">
        <App>
            <pages>
                <Page title="Media operation using SAP UI5 and Google Storage">
                    <content>
                        <VBox class="sapUiSmallMargin">
                            <UploadCollection id="idMultiUploader" maximumFilenameLength="55" maximumFileSize="10" multiple="true" sameFilenameAllowed="false"
                                instantUpload="false" change="onChangeUpload" fileDeleted="onFileDeleted" fileType="png,jpg,jpeg"
                                filenameLengthExceed="onFilenameLengthExceed" fileSizeExceed="onFileSizeExceed" typeMissmatch="onTypeMissmatch"
                                uploadComplete="onUploadComplete" beforeUploadStarts="onBeforeUploadStarts"/>
                            <Link design="Bold" id="idTextArea" target="_blank" href="" text="Download Media"/>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </mvc:View>

     

    Main.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Main", {
    
            /**
             * Called when a controller is instantiated and its View controls (if available) are already created.
             * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
             * @memberOf firebaseApp.firebaseApp.view.Main
             */
            onInit: function (oEvent) {
                this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            },
    
            onChangeUpload: function (oEvent) {
                var that = this;
                var collectionName = "Media";
                // Get File
                var file = oEvent.getParameter("files")[0];
                // Create a Store Ref
                var Firestore = this.getView().getModel("fbModel").getData().fireStorage;
                var storageRef = Firestore.ref(collectionName + '/' + file.name);
                // Upload files
                var task = storageRef.put(file);
                // Get Links
                task.on('state_changed',
                    function progress(snapshot) {},
                    function error(err) {
                        MessageBox.error("File Upload failed for: " + file.name + ". Please uplaod this file again!");
                    },
                    function complete(data) {
    
                    });
                var url = 'https://' + 'firebasestorage.googleapis.com/v0/b/myprojectideas-c2512.appspot.com/o/' + collectionName + '%2F' +
                    file.name +
                    '?alt=media';
                if (url) {
                    that.byId("idTextArea").setHref(url);
                }
            },
    
            onTypeMissmatch: function () {
                MessageBox.error("Only png images allowed. Please uplaod this file again!");
            },
    
            onUploadComplete: function () {
                var collectionName = this.byId("idCollection").getValue();
                if (collectionName === "") {
                    this.byId("idMultiUploader").removeAllItems();
                }
            },
    
        });
    
    });

     

    Output

    Media operation using SAP UI5 and Google Storage

  • CRUD operation using SAP UI5 and Google Firestore | Firebase

    Introduction

    Welcome to the comprehensive guide on performing CRUD (Create, Read, Update, Delete) operations using SAP UI5 and Google Firestore! If you’re looking to build a robust web application with real-time data management capabilities, you’re in the right place.

    In this tutorial, we’ll walk you through the process of integrating SAP UI5, a powerful JavaScript framework for building web applications, with Google Firestore, a flexible and scalable NoSQL database. By combining these technologies, you’ll be able to create a dynamic and interactive application that allows users to perform CRUD operations seamlessly.

    Throughout this tutorial, we’ll cover all aspects of the CRUD operations using SAP UI5 and Google Firestore. We’ll guide you through setting up a project in SAP UI5 and configuring the necessary dependencies. You’ll also learn how to create a collection in Google Firestore to store your application’s data.

    We’ll then delve into the implementation of each CRUD operation. You’ll discover how to create new records, retrieve data, update existing records, and delete entries from the Firestore database using SAP UI5. We’ll provide you with code examples, best practices, and tips to ensure a smooth and efficient implementation.

    Additionally, we’ll explore real-time data synchronization capabilities offered by Google Firestore. You’ll learn how to leverage Firestore’s powerful listeners to automatically update your SAP UI5 application whenever changes occur in the database. This will enable you to build responsive and real-time applications that provide an exceptional user experience.

    By the end of this tutorial, you’ll have a solid understanding of how to perform CRUD operations using SAP UI5 and Google Firestore. You’ll be able to create, read, update, and delete data in your application’s database with ease.

    So, whether you’re a seasoned SAP UI5 developer or just starting your journey in web application development, this tutorial is perfect for you. Get ready to unlock the full potential of SAP UI5 and Google Firestore as you master the art of performing CRUD operations in your applications. Let’s get started on this exciting journey of building dynamic and data-driven web applications!

    Steps to perform CRUD operation using SAP UI5 and Google Firestore

    Sure! Here are the steps to perform CRUD (Create, Read, Update, Delete) operations using SAP UI5 and Google Firestore:

    1. Set up your SAP UI5 project: Create a new SAP UI5 project or use an existing one. Set up the necessary project structure and dependencies.

    2. Set up Google Firestore: Go to the Google Cloud Console (https://console.cloud.google.com/) and create a new project or use an existing one. Enable Firestore for your project and set up the necessary Firestore collections and documents to store your application’s data.

    3. Connect SAP UI5 with Google Firestore: In your SAP UI5 project, create a new JavaScript file (e.g., “firestore.js”) to handle the connection between SAP UI5 and Google Firestore. Import the necessary Firestore libraries and initialize the Firestore client with your project’s configuration.

    4. Implement Create operation: Create a user interface in your SAP UI5 app where users can input data for creating new records. In the “firestore.js” file, implement the logic to add new documents to the Firestore collection using the Firestore client API.

    5. Implement Read operation: Create a user interface to display the existing data from Firestore. In the “firestore.js” file, retrieve the data from the Firestore collection using the Firestore client API and bind it to the SAP UI5 controls for display.

    6. Implement Update operation: Create a user interface to allow users to edit existing records. Implement the logic to update the Firestore documents when the user makes changes using the Firestore client API.

    7. Implement Delete operation: Add functionality to delete records from Firestore. Create a user interface to display the existing records and allow users to delete specific entries. Implement the logic to remove documents from the Firestore collection using the Firestore client API.

    8. Update Rules in Firebase: Rules in Firebase are used to restrict wrong users from performing any CRUD operation over data base. You can read more about it here. As of now, we have removed all the restrictions for testing purposes.

    Rules update in Firebase

    9. Test and refine: Thoroughly test your CRUD operations to ensure they are working correctly. Verify that new records can be created, existing records can be retrieved, updated, and deleted. Handle any error scenarios gracefully and provide appropriate feedback to the user.

    By following these steps, you’ll be able to perform CRUD operations using SAP UI5 and Google Firestore. Remember to consult the documentation for SAP UI5 and Google Firestore for more detailed instructions and best practices.

    UI5 Code to Perform CRUD operation using Google Firestore

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>firebaseApp</title>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"firebaseApp.firebaseApp": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
             <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
    
      <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>
    
      <!-- Add Firebase products that you want to use -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-storage.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-functions.js"></script>
            
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="firebaseApp.firebaseApp" data-id="container" data-settings='{"id" : "firebaseApp"}'></div>
        </body>
    </html>

     

    Firebase.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
    ], function (JSONModel) {
        "use strict";
        return {
            // Firebase-config retrieved from the Firebase-console
            initializeFirebase: function () {
                // Replace with your config here
                const firebaseConfig = {
                    apiKey: "AIzaSyBGCi3pHJZqMmpJEeNjnoII8Ic_BL2v8vU",
                    authDomain: "myprojectideas-c2512.firebaseapp.com",
                    projectId: "myprojectideas-c2512",
                    storageBucket: "myprojectideas-c2512.appspot.com",
                    messagingSenderId: "121838639924",
                    appId: "1:121838639924:web:39794cab14d51551172361"
                };
                // Initialize Firebase with the Firebase-config
                firebase.initializeApp(firebaseConfig);
    
                // Create a Firestore reference
                const firestore = firebase.firestore();
    
                // Create a Authentication reference
                const fireAuth = firebase.auth();
    
                // Get Firebase Instance
                const oFirestore = firebase.firestore;
    
                // Create a Fire Storage reference
                const fireStorage = firebase.storage();
    
                // Create a Fire Functions reference
                const fireFunctions = firebase.app().functions('asia-east2');
    
                // Firebase services object
                const oFirebase = {
                    firestore: firestore,
                    fireAuth: fireAuth,
                    oFirestore: oFirestore,
                    fireStorage: fireStorage,
                    fireFunctions: fireFunctions
                };
    
                // Create a Firebase model out of the oFirebase service object which contains all required Firebase services
                var fbModel = new JSONModel(oFirebase);
    
                // Return the Firebase Model
                return fbModel;
            }
        };
    });

     

    model.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device"
    ], function (JSONModel, Device) {
        "use strict";
    
        return {
    
            createDeviceModel: function () {
                var oModel = new JSONModel(Device);
                oModel.setDefaultBindingMode("OneWay");
                return oModel;
            },
    
            //app Congiguration model
            createAppConfigModel: function () {
                var appData = {
                    "otpSent": false
                };
                var oModel = new JSONModel(appData);
                return oModel;
            }
    
        };
    });

     

    manifest.json

    {
        "_version": "1.12.0",
        "sap.app": {
            "id": "firebaseApp.firebaseApp",
            "type": "application",
            "i18n": "i18n/i18n.properties",
            "applicationVersion": {
                "version": "1.0.0"
            },
            "title": "{{appTitle}}",
            "description": "{{appDescription}}",
            "sourceTemplate": {
                "id": "ui5template.basicSAPUI5ApplicationProject",
                "version": "1.40.12"
            }
        },
        "sap.ui": {
            "technology": "UI5",
            "icons": {
                "icon": "",
                "favIcon": "",
                "phone": "",
                "phone@2": "",
                "tablet": "",
                "tablet@2": ""
            },
            "deviceTypes": {
                "desktop": true,
                "tablet": true,
                "phone": true
            }
        },
        "sap.ui5": {
            "flexEnabled": false,
            "rootView": {
                "viewName": "firebaseApp.firebaseApp.view.Login",
                "type": "XML",
                "async": true,
                "id": "Login"
            },
            "dependencies": {
                "minUI5Version": "1.65.6",
                "libs": {
                    "sap.ui.layout": {},
                    "sap.ui.core": {},
                    "sap.m": {}
                }
            },
            "contentDensities": {
                "compact": true,
                "cozy": true
            },
            "models": {
                "i18n": {
                    "type": "sap.ui.model.resource.ResourceModel",
                    "settings": {
                        "bundleName": "firebaseApp.firebaseApp.i18n.i18n"
                    }
                }
            },
            "resources": {
                "css": [{
                    "uri": "css/style.css"
                }]
            },
            "routing": {
                "config": {
                    "routerClass": "sap.m.routing.Router",
                    "viewType": "XML",
                    "async": true,
                    "viewPath": "firebaseApp.firebaseApp.view",
                    "controlAggregation": "pages",
                    "controlId": "app",
                    "clearControlAggregation": false
                },
                "routes": [{
                    "pattern": "",
                    "name": "",
                    "target": "Login"
                }, {
                    "pattern": "Main",
                    "name": "Main",
                    "target": "Main"
                }],
                "targets": {
                    "Login": {
                        "viewType": "XML",
                        "transition": "slide",
                        "clearControlAggregation": false,
                        "viewId": "Login",
                        "viewName": "Login"
                    },
                    "Main": {
                        "viewType": "XML",
                        "transition": "slide",
                        "clearControlAggregation": false,
                        "viewId": "Main",
                        "viewName": "Main"
                    }
                }
            }
        }
    }

     

    component.js

    sap.ui.define([
        "sap/ui/core/UIComponent",
        "sap/ui/Device",
        "firebaseApp/firebaseApp/model/models",
        "firebaseApp/firebaseApp/js/Firebase"
    ], function (UIComponent, Device, models, Firebase) {
        "use strict";
    
        return UIComponent.extend("firebaseApp.firebaseApp.Component", {
    
            metadata: {
                manifest: "json"
            },
    
            /**
             * The component is initialized by UI5 automatically during the startup of the app and calls the init method once.
             * @public
             * @override
             */
            init: function () {
                // call the base component's init function
                UIComponent.prototype.init.apply(this, arguments);
    
                // enable routing
                this.getRouter().initialize();
    
                // set the device model
                this.setModel(models.createDeviceModel(), "device");
    
                // set the app Config model
                this.setModel(models.createAppConfigModel(), "AppConfig");
    
                //set Firebase Model
                this.setModel(Firebase.initializeFirebase(), "fbModel");
            }
        });
    });

     

    login.view.xml

    <mvc:View controllerName="firebaseApp.firebaseApp.controller.Login" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:core="sap.ui.core">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="OTP Login Integration in SAP UI5 using Google Firebase">
                        <content>
                            <VBox height="100%" alignItems="Center">
                                <HBox height="100%" alignItems="Center">
                                    <Image height="70px" class="sapUiLargeMarginEnd"
                                        src="https://www.loc-online.co.uk/berkshire-loc/wp-content/uploads/sites/23/2020/06/Screenshot-2020-05-28-at-16.35.37-266x300.png"/>
                                    <IconTabBar id="idIconTabBarNoIcons" expanded="{device>/isNoPhone}" selectedKey="mail" class="sapUiResponsiveContentPadding">
                                        <items>
                                            <IconTabFilter text="Mobile Login" key="mobile">
                                                <VBox id="idInitialDetails">
                                                    <Label design="Bold" text="Enter Registered Mobile number" required="true"/>
                                                    <HBox>
                                                        <ComboBox id="idcc" selectedKey="65" width="90px" class="sapUiTinyMarginEnd">
                                                            <core:Item key="65" text="+65"/>
                                                            <core:Item key="60" text="+60"/>
                                                            <core:Item key="62" text="+62"/>
                                                            <core:Item key="91" text="+91"/>
                                                        </ComboBox>
                                                        <Input width="200px" id="idMob" required="true" type="Number" placeholder="0000000" submit="ongetOTP"/>
                                                    </HBox>
                                                    <HBox visible="{= ${AppConfig>/otpSent} === true ? false : true}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Get OTP" press="ongetOTP"/>
                                                        <Button width="145px" text="Reset" press="onReset"/>
                                                    </HBox>
                                                    <Label visible="{AppConfig>/otpSent}" design="Bold" text="OTP" required="true"/>
                                                    <Input visible="{AppConfig>/otpSent}" width="300px" id="idOTP" required="true" submit="onASignin"/>
                                                    <HBox visible="{AppConfig>/otpSent}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Sign In" press="onASignin"/>
                                                        <Button width="145px" text="Resend OTP" press="ongetOTP"/>
                                                    </HBox>
                                                </VBox>
                                            </IconTabFilter>
                                        </items>
                                    </IconTabBar>
                                    <!--Code for Recaptcha-->
                                    <core:HTML content='&lt;div id=&quot;sign-in-button&quot;&gt;&lt;/div&gt;'></core:HTML>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    login.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Login", {
            onInit: function () {
                this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            },
    
            onAfterRendering: async function () {
                sap.ui.core.BusyIndicator.show();
                await this.onGetRecaptcha();
                sap.ui.core.BusyIndicator.hide();
            },
    
            onGetRecaptcha: function (oEvent) {
                var that = this;
                sap.ui.core.BusyIndicator.show();
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
                    'size': 'invisible',
                    'callback': (response) => {
                        // reCAPTCHA solved, allow signInWithPhoneNumber.
                        sap.ui.core.BusyIndicator.hide();
                    }
                });
            },
    
            ongetOTP: function () {
                sap.ui.core.BusyIndicator.show();
                var appVerifier = window.recaptchaVerifier;
                var that = this;
                var cc = this.byId("idcc")._getSelectedItemText();
                var mob = this.byId("idMob").getValue();
                mob = cc + mob;
                this.phone = mob;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                firebase.auth().signInWithPhoneNumber(mob, appVerifier)
                    .then((confirmationResult) => {
                        sap.ui.core.BusyIndicator.hide();
                        // SMS sent. Prompt user to type the code from the message, then sign the
                        // user in with confirmationResult.confirm(code).
                        window.confirmationResult = confirmationResult;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", true);
                    }).catch((error) => {
                        sap.ui.core.BusyIndicator.hide();
                        // Error; SMS not sent
                        var errorMessage = error.message;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
                        MessageBox.error(errorMessage);
                    });
            },
    
            onASignin: async function (oEvent) {
                sap.ui.core.BusyIndicator.show();
                var that = this;
                var otp = this.byId("idOTP").getValue();
                var errorMessage = "";
                // Create a Fireauth Auth reference
                var oModel = that.getView().getModel("fbModel").getData();
                localStorage.setItem("oModelFireAuth", JSON.stringify(oModel.fireAuth));
                var fireAuth = oModel.fireAuth;
                var firestoreData = oModel.firestore;
                var fireFunctions = oModel.fireFunctions;
                //get Token for the call
                window.confirmationResult.confirm(otp).then(async(result) => {
                    await fireAuth.currentUser.getIdToken( /* forceRefresh */ true).then(async function (idToken) {
                        MessageBox.success("You are logged in via OTP!");
                        that.oRouter.navTo("Main");
                        sap.ui.core.BusyIndicator.hide();
                    }).catch(function (error) {
                        sap.ui.core.BusyIndicator.hide();
                        that.onReset();
                        MessageBox.error("User is not registered, kindly contact Admin.");
                        fireAuth.signOut().then(function (success) {
                            // MessageBox.error("You are logged out, refresh and try again!");
                        }).catch(function (error) {
                            MessageBox.error(error.error.Error);
                        });
                    });
                }).catch((error) => {
                    // User couldn't sign in (bad verification code?)
                    sap.ui.core.BusyIndicator.hide();
                    errorMessage = error.message;
                    MessageBox.error(errorMessage);
                    fireAuth.signOut().then(function (success) {
                        // jQuery.sap.storage.put(that.userID, null);
                    }).catch(function (error) {});
                });
            },
    
            onReset: function (oEvent) {
                this.byId("idOTP").setValue("");
                this.byId("idMob").setValue("");
                this.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
            }
        });
    });

     

    main.view.xml

    <mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"
        controllerName="firebaseApp.firebaseApp.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml">
        <App>
            <pages>
                <Page title="CRUD operation using SAP UI5 and Google Firestore">
                    <content>
                        <VBox class="sapUiSmallMargin">
                            <f:SimpleForm id="SimpleFormOrg" editable="true" layout="ResponsiveGridLayout" title="Organizations" 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 of Organization"/>
                                    <Input id="idOrgName"/>
                                    <Button text="Add" type="Accept" press="onAddOrg"/>
                                </f:content>
                            </f:SimpleForm>
                            <Table id="idOrgTable" inset="false" items="{/orgs}" sticky="ColumnHeaders,HeaderToolbar" class="sapFDynamicPageAlignContent" width="auto">
                                <columns>
                                    <Column>
                                        <Text text="ID"/>
                                    </Column>
                                    <Column>
                                        <Text text="Name of Organization"/>
                                    </Column>
                                    <Column vAlign="Right">
                                        <Text text="New Name"/>
                                    </Column>
                                    <Column vAlign="Right">
                                        <Text text="Perform Operations"/>
                                    </Column>
                                </columns>
                                <items>
                                    <ColumnListItem>
                                        <cells>
                                            <Text text="{ID}"/>
                                            <Text text="{name}"/>
                                            <Input value="{newName}"/>
                                            <HBox alignItems="Center" justifyContent="Start">
                                                <Button icon="sap-icon://edit" press="onUpdate"/>
                                                <Button icon="sap-icon://delete" press="onDelete"/>
                                            </HBox>
                                        </cells>
                                    </ColumnListItem>
                                </items>
                            </Table>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </mvc:View>

     

    main.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Main", {
    
            /**
             * Called when a controller is instantiated and its View controls (if available) are already created.
             * Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
             * @memberOf firebaseApp.firebaseApp.view.Main
             */
            onInit: function (oEvent) {
                this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
            },
    
            onAfterRendering: async function () {
                this.onSelectOrg();
            },
    
            onSelectOrg: function () {
                var that = this;
                var oItems = {};
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                collRefUsers.onSnapshot(collection => {
                    var aItems = collection.docs.map(function (docUser) {
                        var finalData = docUser.data();
                        finalData.ID = docUser.id;
                        return finalData;
                    });
                    oItems.orgs = aItems;
                    // Create and set the created object to the the UserModel
                    var oModel = new sap.ui.model.json.JSONModel(oItems);
                    this.getView().byId("idOrgTable").setModel(oModel);
                    sap.ui.core.BusyIndicator.hide();
                }, error => {
                    sap.ui.core.BusyIndicator.hide();
                    // MessageBox.error("Missing or insufficient permissions!");
                });
    
            },
    
            onAddOrg: function () {
                var that = this;
                var org = this.byId("idOrgName").getValue();
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                if (org) {
                    collRefUsers.doc(org).set({
                        name: org
                    }).then(function (success) {
                        sap.m.MessageBox.success("Organization Added Successfully!");
                        that.byId("idOrgName").setValue("");
                    }).catch(function (error) {
                        // Handle Errors here.
                        var errorMessage = error.message;
                        MessageBox.error(errorMessage);
                    });
                } else {
                    MessageBox.error("Enter an Organization Name to Add!");
                }
            },
    
            onDelete: function (oEvent) {
                var that = this;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                var selected = oEvent.getSource().getBindingContext().getObject().ID;
                sap.m.MessageBox.confirm("Do you want to Delete selected Organization?", function (rValue) {
                    if (rValue == "OK") {
                        collRefUsers.doc(selected).delete().then(function () {
                            sap.m.MessageBox.success("Organization Deleted!");
                        }).catch(function (error) {
                            // Handle Errors here.
                            var errorMessage = error.message;
                            MessageBox.error(errorMessage);
                        });
                    } else {}
                });
            },
    
            onUpdate: function (oEvent) {
                var that = this;
                var selected = oEvent.getSource().getBindingContext().getObject().name;
                var updated = oEvent.getSource().getBindingContext().getObject().newName;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                var collRefUsers = firestoreData.collection("Organization");
                sap.m.MessageBox.confirm("Do you want to Update selected Organization?", function (rValue) {
                    if (rValue == "OK") {
                        collRefUsers.doc(selected).update({
                            name: updated
                        }).then(function (success) {
                            sap.m.MessageBox.success("Organization Updated Successfully!");
                        }).catch(function (error) {
                            // Handle Errors here.
                            var errorMessage = error.message;
                            MessageBox.error(errorMessage);
                        });
                    } else {}
                });
            }
    
        });
    
    });

    Output

    CRUD operation using SAP UI5 and Google Firestore

  • OTP Login Integration in SAP UI5 using Google Firebase

    Introduction

    Welcome to the ultimate guide for integrating OTP (One-Time Password) login functionality in SAP UI5 using the power of Google Firebase! If you’re looking to enhance the security and user experience of your SAP UI5 application, implementing OTP login is a fantastic choice.

    In this comprehensive tutorial, we will walk you through the step-by-step process of seamlessly integrating OTP login functionality into your SAP UI5 application using Google Firebase. By leveraging Firebase’s robust authentication services, you can provide users with a secure and convenient login experience.

    In the world of modern web applications, OTP login has become increasingly popular due to its effectiveness in preventing unauthorized access. With OTP login, users receive a unique, time-sensitive code via SMS or email, which they enter to authenticate themselves. This adds an extra layer of security to your application.

    Throughout this tutorial, we will cover everything you need to know to successfully integrate OTP login in your SAP UI5 application. Starting from setting up a Firebase project and configuring the necessary Firebase services, to implementing OTP generation and verification logic within your application, we’ve got you covered.

    You will learn how to leverage Firebase Authentication and the Firebase SDK to generate and send OTP codes to users. We will guide you through the process of capturing and validating OTPs, ensuring a smooth and secure login process. Additionally, we’ll explore best practices for handling error scenarios and improving the overall user experience.

    By the end of this tutorial, you’ll have a fully functional OTP login system integrated seamlessly into your SAP UI5 application, powered by the secure and reliable infrastructure of Google Firebase.

    So, if you’re ready to take your SAP UI5 application’s security to the next level, join us in this exciting journey of OTP login integration. Let’s get started on creating a secure, user-friendly, and highly-protected login system for your SAP UI5 application using Google Firebase.

    OTP Login Integration in SAP UI5 using Google Firebase

    Sure! Here are the steps to do OTP login integration in SAP UI5 using Google Firebase:

    1. Set up a Firebase project: Create a new Firebase project or use an existing one. Go to the Firebase console (https://console.firebase.google.com/) and create a new project. Enable the Firebase Authentication service for your project.

    Enable Authentication in Google Firebase

    Enable the test OPT Mobile Number in Google Firebase:

    Test OPT Mobile Number in Google Firebase

    2. Install the Firebase SDK: In your SAP UI5 project, open the terminal or command prompt and navigate to the project directory. Run the following command to install the Firebase JavaScript SDK:

    npm install firebase

    3. Initialize Firebase: Create a new JavaScript file in your SAP UI5 project, such as “firebase.js”. Import the Firebase SDK and initialize Firebase with your project’s configuration. Obtain the Firebase configuration object from the Firebase console by navigating to Project Settings > General > Your apps > Firebase SDK snippet. Copy the code snippet for the web app configuration and paste it into your “firebase.js” file.

    4. Generate and send OTP: Implement a user interface in your SAP UI5 app where users can enter their phone number or email address. When the user requests an OTP, use the Firebase Authentication SDK to generate and send the OTP to the provided phone number or email address.

    5. Verify OTP: Create another user interface where users can enter the OTP they received. Use the Firebase Authentication SDK to verify the entered OTP against the generated OTP. If the verification is successful, proceed with the login process.

    6. Handle authentication events: Implement Firebase authentication state listeners to detect when a user is logged in or logged out. Update your SAP UI5 app’s UI and behavior accordingly based on the user’s authentication status.

    7. Test and refine: Test the OTP login integration thoroughly to ensure a smooth user experience. Verify that OTPs are generated and delivered correctly and that the verification process is working as expected. Handle error scenarios gracefully and provide appropriate feedback to the user.

    By following these steps, you’ll be able to integrate OTP login functionality into your SAP UI5 application using Google Firebase. Remember to consult the Firebase documentation and the SAP UI5 guidelines for more detailed instructions and best practices. Happy coding!

    UI5 Code to Integrate OTP Login using Google Firebase

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
            <title>HealthBridge Doctor</title>
              <link rel="icon" type="image/x-icon" href="https://healthbridge-intl.com/wp-content/uploads/2021/09/cropped-Colour-Logo-Only-1-32x32.png">
            <script id="sap-ui-bootstrap"
                src="https://openui5.hana.ondemand.com/1.96.7/resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"Healthbridge-Doctor.Healthbridge-Doctor": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
    <!--Check if device is mobile: Create a media condition that targets viewports at least 768px wide-->
    <script>
    const mediaQuery = window.matchMedia('(max-width: 768px)')
    // Check if the media query is true
    if (mediaQuery.matches) {
      // Then trigger an alert
      alert('This device is not supported, contact Admin!')
      window.location = 'https://healthbridge-intl.com/';
    }
    </script>
            <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
    <script type="text/javascript" src="https://unpkg.com/virgil-crypto@^4.0.0/dist/browser.umd.js"></script>
       <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
    
      <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>
    
      <!-- Add Firebase products that you want to use -->
      <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-auth.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-database.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.23.0/firebase-storage.js"></script>
      <script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-functions.js"></script>
      
      <!-- Agora Scripts -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="Healthbridge-Doctor.Healthbridge-Doctor" data-id="container" data-settings='{"id" : "Healthbridge-Doctor"}'></div>
        </body>
    </html>

     

    Model.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device"
    ], function (JSONModel, Device) {
        "use strict";
    
        return {
    
            createDeviceModel: function () {
                var oModel = new JSONModel(Device);
                oModel.setDefaultBindingMode("OneWay");
                return oModel;
            },
    
            //app Congiguration model
            createAppConfigModel: function () {
                var appData = {
                    "otpSent": false
                };
                var oModel = new JSONModel(appData);
                return oModel;
            }
    
        };
    });

     

    Firebase.js

    sap.ui.define([
        "sap/ui/model/json/JSONModel",
    ], function (JSONModel) {
        "use strict";
        return {
            // Firebase-config retrieved from the Firebase-console
            initializeFirebase: function () {
                // Replace with your config here
                const firebaseConfig = {
                    apiKey: "AIzaSyBGCi3pHJZqMmpJEeNjnoII8Ic_BL2v8vU",
                    authDomain: "myprojectideas-c2512.firebaseapp.com",
                    projectId: "myprojectideas-c2512",
                    storageBucket: "myprojectideas-c2512.appspot.com",
                    messagingSenderId: "121838639924",
                    appId: "1:121838639924:web:39794cab14d51551172361"
                };
                // Initialize Firebase with the Firebase-config
                firebase.initializeApp(firebaseConfig);
    
                // Create a Firestore reference
                const firestore = firebase.firestore();
    
                // Create a Authentication reference
                const fireAuth = firebase.auth();
    
                // Get Firebase Instance
                const oFirestore = firebase.firestore;
    
                // Create a Fire Storage reference
                const fireStorage = firebase.storage();
    
                // Create a Fire Functions reference
                const fireFunctions = firebase.app().functions('asia-east2');
    
                // Firebase services object
                const oFirebase = {
                    firestore: firestore,
                    fireAuth: fireAuth,
                    oFirestore: oFirestore,
                    fireStorage: fireStorage,
                    fireFunctions: fireFunctions
                };
    
                // Create a Firebase model out of the oFirebase service object which contains all required Firebase services
                var fbModel = new JSONModel(oFirebase);
    
                // Return the Firebase Model
                return fbModel;
            }
        };
    });

     

    Component.js

    sap.ui.define([
        "sap/ui/core/UIComponent",
        "sap/ui/Device",
        "firebaseApp/firebaseApp/model/models",
        "firebaseApp/firebaseApp/js/Firebase"
    ], function (UIComponent, Device, models, Firebase) {
        "use strict";
    
        return UIComponent.extend("firebaseApp.firebaseApp.Component", {
    
            metadata: {
                manifest: "json"
            },
    
            /**
             * The component is initialized by UI5 automatically during the startup of the app and calls the init method once.
             * @public
             * @override
             */
            init: function () {
                // call the base component's init function
                UIComponent.prototype.init.apply(this, arguments);
    
                // enable routing
                this.getRouter().initialize();
    
                // set the device model
                this.setModel(models.createDeviceModel(), "device");
    
                // set the app Config model
                this.setModel(models.createAppConfigModel(), "AppConfig");
    
                //set Firebase Model
                this.setModel(Firebase.initializeFirebase(), "fbModel");
            }
        });
    });

     

    Login.view.xml

    <mvc:View controllerName="firebaseApp.firebaseApp.controller.Login" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml" xmlns:core="sap.ui.core">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="OTP Login Integration in SAP UI5 using Google Firebase">
                        <content>
                            <VBox height="100%" alignItems="Center">
                                <HBox height="100%" alignItems="Center">
                                    <Image height="70px" class="sapUiLargeMarginEnd"
                                        src="https://www.loc-online.co.uk/berkshire-loc/wp-content/uploads/sites/23/2020/06/Screenshot-2020-05-28-at-16.35.37-266x300.png"/>
                                    <IconTabBar id="idIconTabBarNoIcons" expanded="{device>/isNoPhone}" selectedKey="mail" class="sapUiResponsiveContentPadding">
                                        <items>
                                            <IconTabFilter text="Mobile Login" key="mobile">
                                                <VBox id="idInitialDetails">
                                                    <Label design="Bold" text="Enter Registered Mobile number" required="true"/>
                                                    <HBox>
                                                        <ComboBox id="idcc" selectedKey="65" width="90px" class="sapUiTinyMarginEnd">
                                                            <core:Item key="65" text="+65"/>
                                                            <core:Item key="60" text="+60"/>
                                                            <core:Item key="62" text="+62"/>
                                                            <core:Item key="91" text="+91"/>
                                                        </ComboBox>
                                                        <Input width="200px" id="idMob" equired="true" type="Number" placeholder="0000000" submit="ongetOTP"/>
                                                    </HBox>
                                                    <HBox visible="{= ${AppConfig>/otpSent} === true ? false : true}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Get OTP" press="ongetOTP"/>
                                                        <Button width="145px" text="Reset" press="onReset"/>
                                                    </HBox>
                                                    <Label visible="{AppConfig>/otpSent}" design="Bold" text="OTP" required="true"/>
                                                    <Input visible="{AppConfig>/otpSent}" width="300px" id="idOTP" required="true" submit="onASignin"/>
                                                    <HBox visible="{AppConfig>/otpSent}">
                                                        <Button width="145px" class="sapUiTinyMarginEnd" text="Sign In" press="onASignin"/>
                                                        <Button width="145px" text="Resend OTP" press="ongetOTP"/>
                                                    </HBox>
                                                </VBox>
                                            </IconTabFilter>
                                        </items>
                                    </IconTabBar>
                                    <!--Code for Recaptcha-->
                                    <core:HTML content='&lt;div id=&quot;sign-in-button&quot;&gt;&lt;/div&gt;'></core:HTML>
                                </HBox>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Login.controller.js

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/MessageBox"
    ], function (Controller, MessageBox) {
        "use strict";
    
        return Controller.extend("firebaseApp.firebaseApp.controller.Login", {
            onInit: function () {
    
            },
    
            onAfterRendering: async function () {
                sap.ui.core.BusyIndicator.show();
                await this.onGetRecaptcha();
                sap.ui.core.BusyIndicator.hide();
            },
    
            onGetRecaptcha: function (oEvent) {
                var that = this;
                sap.ui.core.BusyIndicator.show();
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
                    'size': 'invisible',
                    'callback': (response) => {
                        // reCAPTCHA solved, allow signInWithPhoneNumber.
                        sap.ui.core.BusyIndicator.hide();
                    }
                });
            },
    
            ongetOTP: function () {
                sap.ui.core.BusyIndicator.show();
                var appVerifier = window.recaptchaVerifier;
                var that = this;
                var cc = this.byId("idcc")._getSelectedItemText();
                var mob = this.byId("idMob").getValue();
                mob = cc + mob;
                this.phone = mob;
                // Create a Fireauth Auth reference
                var oModel = this.getView().getModel("fbModel").getData();
                var fireAuth = oModel.fireAuth;
                fireAuth.useDeviceLanguage();
                var firestoreData = oModel.firestore;
                firebase.auth().signInWithPhoneNumber(mob, appVerifier)
                    .then((confirmationResult) => {
                        sap.ui.core.BusyIndicator.hide();
                        // SMS sent. Prompt user to type the code from the message, then sign the
                        // user in with confirmationResult.confirm(code).
                        window.confirmationResult = confirmationResult;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", true);
                    }).catch((error) => {
                        sap.ui.core.BusyIndicator.hide();
                        // Error; SMS not sent
                        var errorMessage = error.message;
                        that.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
                        MessageBox.error(errorMessage);
                    });
            },
    
            onASignin: async function (oEvent) {
                sap.ui.core.BusyIndicator.show();
                var that = this;
                var otp = this.byId("idOTP").getValue();
                var errorMessage = "";
                // Create a Fireauth Auth reference
                var oModel = that.getView().getModel("fbModel").getData();
                localStorage.setItem("oModelFireAuth", JSON.stringify(oModel.fireAuth));
                var fireAuth = oModel.fireAuth;
                var firestoreData = oModel.firestore;
                var fireFunctions = oModel.fireFunctions;
                //get Token for the call
                window.confirmationResult.confirm(otp).then(async(result) => {
                    await fireAuth.currentUser.getIdToken( /* forceRefresh */ true).then(async function (idToken) {
                        MessageBox.success("You are logged in via OTP!");
                        sap.ui.core.BusyIndicator.hide();
                    }).catch(function (error) {
                        sap.ui.core.BusyIndicator.hide();
                        that.onReset();
                        MessageBox.error("User is not registered, kindly contact Admin.");
                        fireAuth.signOut().then(function (success) {
                            // MessageBox.error("You are logged out, refresh and try again!");
                        }).catch(function (error) {
                            MessageBox.error(error.error.Error);
                        });
                    });
                }).catch((error) => {
                    // User couldn't sign in (bad verification code?)
                    sap.ui.core.BusyIndicator.hide();
                    errorMessage = error.message;
                    MessageBox.error(errorMessage);
                    fireAuth.signOut().then(function (success) {
                        // jQuery.sap.storage.put(that.userID, null);
                    }).catch(function (error) {});
                });
            },
    
            onReset: function (oEvent) {
                this.byId("idOTP").setValue("");
                this.byId("idMob").setValue("");
                this.getOwnerComponent().getModel("AppConfig").setProperty("/otpSent", false);
            }
        });
    });

     

    Output

    OTP Login Output UI5