Utilizing SAPUI5 to integrate OData and other web services within a unified table

This inquiry pertains to developing SAPUI5 with the SAP Web IDE. The goal is to integrate an OData Service with a web service accessed via the POST Method. Essentially, the process involves retrieving a list from the OData Service (linked to a backend-SAP system) and displaying it in a table element, which currently functions as intended.

Now, for each row in the table, there is a need to call a web service using the POST method to obtain additional data that should be displayed within the same row. For instance:

If Row Column 1 contains value A and Column 2 contains value B, by passing these values to the web service, it should return "For A and B, the result is X." This X value needs to be shown in another column of the same row.

How can this desired functionality be accomplished? Are there any examples or references you can provide?

Answer №1

Generate a JSON structure based on the data obtained from your AJAX POST response. Connect the specific cell in your table to this newly created JSON model. To filter and display data from the JSON model based on the OData values for each row, utilize a formatter function with custom logic.

Explore an example showcasing data retrieval from Northwind along with a fabricated JSON model: https://jsbin.com/racenaqoki/edit?html,output

Demonstrate a real-time AJAX call scenario: https://jsbin.com/jivomamuvi/edit?html,output

<html>
<head>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta charset="utf-8">

    <title>MVC with XmlView</title>

    <!-- Load UI5, select "blue crystal" theme and the "sap.m" control library -->
    <script id='sap-ui-bootstrap'
        src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js'
        data-sap-ui-theme='sap_bluecrystal'
        data-sap-ui-libs='sap.m'
        data-sap-ui-xx-bindingSyntax='complex'></script>


    <!-- DEFINE RE-USE COMPONENTS - NORMALLY DONE IN SEPARATE FILES -->

    <!-- define a new (simple) View type as an XmlView
     - using data binding for the Button text
     - linking a controller method to the Button's "press" event
     - incorporating some plain HTML elements
     note: usually stored in a separate file -->

    <script id="view1" type="sapui5/xmlview">
    <mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc" controllerName="my.own.controller">
        <Page>
        <Table items="{/Orders}" updateFinished="onTableUpdateFinished">
      <columns>
          <Column >
              <Text text="Value Obtained From OData"/>
          </Column>
          <Column>
              <Text text="Value Extracted From AJAX Response"/>
          </Column>
      </columns>
      <items>
          <ColumnListItem>
            <cells>
              <ObjectIdentifier title="{CustomerID}"/>
              <ObjectIdentifier text="{parts:[{path:'CustomerID'}, {path:'myOtherModel>/'}], formatter: '.myFormatter'}"/>
            </cells>
        </ColumnListItem>
      </items>
    </Table>
        </Page>
    </mvc:View> 
</script>


    <script>
        // defining a basic Controller type
        sap.ui.controller("my.own.controller", {
          onInit: function(){
              var myOtherModel = new sap.ui.model.json.JSONModel();
              this.getView().setModel(myOtherModel, "myOtherModel");

              //Perform an AJAX call here to retrieve data through a POST request
              /*
                $.ajax({
          type: "POST",
          url: url,
          data: data,
          success: this.ajaxSuccess,
          dataType: dataType
        });
              */

              //Simulate a successful API response by providing sample data
              var data = {
                VINET: {
                  message: "VINET Rocks!!"
                },
                WARTH: {
                  message: "WARTH is good company!!"
                },
                RICSU: {
                  message: "RICSU I don't like"
                },
                HANAR: {
                  message: "HANAR was my first customer"
                }
              }
              this.ajaxSuccess(data);
            },

            ajaxSuccess: function(data){
              this.getView().getModel("myOtherModel").setData(data)
            },

            myFormatter: function(sCustomerID, otherModelData){
              // Custom formatter executed per table row
              // First parameter holds value bound in the initial column
              // Second parameter includes node to extract from the second model

              //Implement desired operations and return output for 'text' property
              if(otherModelData[sCustomerID]){
                // Check if given Customer ID has corresponding node in second model, return its message
                return otherModelData[sCustomerID].message;
              }
              //Else return empty string
              return "";
            }
        });



        /*** APPLICATION CODE ***/
        // Establish a Model and link it to the View
        // Utilizing HEROKU Proxy to handle potential CORS restrictions
        var uri = "https://cors-anywhere.herokuapp.com/services.odata.org/Northwind/Northwind.svc"; // local proxy for cross-domain access
        var oNorthwindModel = new sap.ui.model.odata.ODataModel(uri, {
            maxDataServiceVersion: "2.0"
        }); 
        // Create the View instance
        var myView = sap.ui.xmlview({viewContent:jQuery('#view1').html()}); // accessing the HTML inside the script tag above
        // Set the OData Model
        myView.setModel(oNorthwindModel);


        myView.placeAt('content');
    </script>

</head>
<body id='content' class='sapUiBody'>
</body>

Answer №2

To enhance your oData service, consider adding the "webservice_result" property to the entity. Within the Data Provider Class, keep this property empty and only return values for "A" and "B".

Once you retrieve the results from the oData service, make an ajax call to another webservice with values A and B. Upon receiving the result, update the "webservice_result" property of the specific row (entity) using

oDataModel.setProperty("row_x/webservice_result", value)

For more information, refer to:

jQuery.ajax

setProperty method

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on creating an API for updating a field in MongoDB database

Here are the details of my fields. { "_id" : ObjectId("5b7f93224fc3b140983ea775"), "city" : "visakapatnam", "area" : "mvp", "zone" : "zone II", "ward" : "ward I", "status" : false, "createdAt" : ISODate("2018-08-24T05:09:54.279 ...

Fill Datalist with Database Information

As a beginner in javascript and php, I am trying to populate a datalist from a mysql table. However, I am facing some difficulties with the relevant codes provided below. Although I can fetch data from the database, I am struggling to display them in the d ...

Encountering issues after setting up JSON API in Swift

I have successfully implemented most of the functionality. However, when I build the project and execute the function, it processes the API content before crashing abruptly. Here is the updated code snippet: // // GamesTableViewController.swift // Footb ...

Ways to expand the inheritance of a family's assets in the next generation

I am facing an issue with the following code snippet: class Table { get pagination () { return { get item () { return { log (s : string) { console.log(s); ...

Encapsulate string type object properties within arrays

Currently, I am immersed in learning React and Javascript, and I am in search of the most elegant approach to convert a simple object into an array of objects, even if it only consists of a single value. This specific object is nested within another object ...

Obtaining connection data in jsPlumb can be accomplished through a variety of

I have created a compact table of nodes that allow me to drag and drop connections or manually input node IDs to establish connections between them. Despite searching through the documentation and scouring the internet for examples, I am struggling to fin ...

What is the reason for the addEventListener function not being able to access global variables?

I have set up an event listener function to utilize popcorn.js for displaying subtitles. Additionally, I have created functions that are unrelated to popcorn.js outside of the event listener and declared a global variable array. However, when attempting ...

Issue: Corrupted zip file - unable to locate the end of central directory for XLSX documents

I've encountered an issue while trying to read my Excel file using XLSX npm. The error message I received is 'Corrupted zip : can't find end of central directory' This is the error that was thrown: Error: Corrupted zip : can't fi ...

What is the best way to conceal a lengthy description and create a toggle feature in React JS?

Having an issue with my ReactJS application. It consists of card items with brief descriptions that I want to expand into full details when clicking a button. The goal is to toggle between short and long descriptions, providing users with flexibility in ...

The JW Player unexpectedly restarts when the CSS position is set to fixed in Firefox and Safari 5.0

I've created a script that dynamically changes the positioning of a div element from static to fixed when the scroll bar reaches it. You can see this in action on my website here: example, where a floating video in the right column stays fixed as you ...

Can one access non-static methods within React Navigation's navigationOptions?

Within my form, I am trying to position a submit button to the right of the header that triggers the same method as the submit button located at the bottom of the form. React Navigation necessitates the declaration of a static method named navigationOptio ...

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...

Utilizing data attributes instead of IDs for connecting buttons and tabs in Javascript tab navigation

I'm currently exploring a new approach to creating Javascript tabs by utilizing data attributes instead of IDs to connect the tab with its content. Here's the concept in action: When clicking on a <button class="tab" data-tab-trigger="1"> ...

Internet Explorer captures XML response

Currently, I am working with a form that has an iframe specified as its target. As part of the form submission process, I receive a response in XML format and have Javascript code to analyze this response. An issue I encountered is that when using IE, th ...

Tips for extracting values from a JSON object in Angular when dealing with a JSON string

Storing column values as a json string in the DB table and then sending them to the front end as a json object. [ { "jobId":"efe0ace0-8ed9-45ff-9232-974cbdc89b86", "jobType":"TestExecutionJob", "nextRun":"N/A", "lastRun":"20 ...

Error: The index.js file could not be located within the React application being used by Express with Node

I am having an issue with setting up my own express server for a React app in production. I keep getting a 404 error for the index.js file which contains my React js script. Here is the folder structure I am working with: server.js +public | index.html | ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...

Tips for integrating Bootstrap JavaScript into a React project

I am encountering an issue while trying to incorporate Bootstrap JavaScript into my web app. I have successfully included the CSS, but I am facing difficulties with Bootstrap JavaScript for components like modals and alerts. My package.json includes: "boo ...

The syntax for importing JSON in JavaScript ES6 is incredibly straightforward and

Whenever I attempt to write my code following the ES6 standard and try to import a .json file, it ends up failing on me. import JsonT from "../../Data/t.json" //not functioning as expected var JsonT = require('../../Data/t.json'); //works fine ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...