Feature to insert a fresh row into SAPUI5 table

I've been attempting to insert new rows into a SAPUI5 table with the click of a button. Despite watching numerous tutorials online, I haven't found one that fits my specific situation.

Currently, the JSON data is loaded via a mock server with the following structure for testing purposes:

{
  "Invoices": [
    {
      "ProductName": "Pineapple",
      "Quantity": 21,
      "ExtendedPrice": 87.2000,
      "ShipperName": "Fun Inc.",
      "ShippedDate": "2015-04-01T00:00:00",
      "Status": "A"
    },
    ...
  ]
}

The table definition in the view looks like this:

<mvc:View controllerName="stepbystep.demo.wt.controller.App" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:core="sap.ui.core"
xmlns:html="http://www.w3.org/1999/xhtml" displayBlock="true">
<Table id="ins" items="{ path : 'invoice>/Invoices', sorter : { path : 'ProductName' } }">
    <headerToolbar>
        <Toolbar>
            <Button icon="sap-icon://add" text="Row" press="addRow"/>
            <Button icon="sap-icon://display" text="Rows" press="fetchRecords"/>
        </Toolbar>
    </headerToolbar>
    <columns>
        <Column hAlign="Right" minScreenWidth="Small" demandPopin="true" width="4em">
            <Text text="{i18n>columnQuantity}"/>
        </Column>
        <Column>
            <Text text="{i18n>columnName}"/>
        </Column>
        <Column minScreenWidth="Small" demandPopin="true">
            <Text text="{i18n>columnStatus}"/>
        </Column>
        <Column minScreenWidth="Tablet" demandPopin="false">
            <Text text="{i18n>columnSupplier}"/>
        </Column>
        <Column hAlign="Right">
            <Text text="{i18n>columnPrice}"/>
        </Column>
    </columns>
    <items>
        <ColumnListItem type="Navigation" press="onPress">
            <cells>
                <ObjectNumber number="{invoice>Quantity}" emphasized="false"/>
                <ObjectIdentifier title="{invoice>ProductName}"/>
                <Text text="{ path: 'invoice>Status', formatter: '.formatter.statusText' }"/>
                <Text text="{invoice>ShipperName}"/>
                <ObjectNumber
                    number="{ parts: [{path: 'invoice>ExtendedPrice'}, {path: 'view>/currency'}], type: 'sap.ui.model.type.Currency', formatOptions: { showMeasure: false } }"
                    unit="{view>/currency}" state="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Success' }"/>
            </cells>
        </ColumnListItem>
    </items>
</Table>

In the controller, there is a function that includes the following code snippet (only the part that functions properly is pasted here):

addRow: function() {
    var oList = this.getView().byId("ins");
    var oDt = oList.getBinding("items").getModel().oData;
}

How should I proceed from here? I attempted using push() on the model but encountered errors. One option I'm considering is adding an empty row to oDt and binding it to the table, although I'm unsure about the best approach for this task.

EDIT: A link was shared regarding "How to Add a New ColumnListItem to a Table," which may be relevant, but the proposed solution doesn't seem to match my requirements. As a newcomer to SAPUI5, any guidance would be appreciated.

Answer №1

Custom JSON Model:

this.getData().getModel('account').getValue('/Accounts').add({/* new account data */})

Custom OData Model:

this.getData().getModel('account').create('/Accounts', {/* new account data */})

or

this.getData().getModel('account').createNewEntry('/Accounts', {/* new account data */})
this.getData().getModel('account').saveChanges();

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

Issue with Angular: PDF rendering delayed until window resize

Recently, I encountered an issue with rendering a PDF in Chrome while using an AJAX call with Angular. Strangely, the PDF would only show up in the browser if I resized the window or opened the console. Surprisingly, everything worked fine in Firefox. Jav ...

I am looking to preload a separate webpage prior to the HTML loading in AngularJS

I am looking to implement a feature in my AngularJS app where a different webpage (e.g. google.com) will be loaded based on the response of a REST API before any default HTML content is displayed. I have attempted to make a REST service call within a fact ...

Guidelines for sending an array from a Laravel Controller through AJAX and generating a button based on the received data

Before making a selection, I click on the Color button: <form class="form form-variant"> {{ csrf_field() }} <button type="submit" class="btn btn-success che ...

Reprinting information from my server / overlooked a task

After saving "Ben and Jerry's" to my database and retrieving it later for editing/resaving in an input tag, I am encountering an issue. Ben & Jerry&#39;s What could be the problem? (I have noticed that the "&" is correctly translated but ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

Alter the app's entire background color in React.js with a button click

I am facing an issue with changing the background color of my entire React App when a button is clicked. Currently, I am able to change the color of the button itself but not the background. I have imported the App.css file into my project and I am looking ...

Having Trouble with Your Instafeed Script

I've been working on a project that involves integrating an Instagram feed into a website. However, I'm facing difficulties getting it to function properly. Here's the code that I have implemented. <script type="text/javascript"> ...

A guide on converting a JSON array into CSV format while customizing attributes

I'm currently developing a Node.js application using JavaScript. I have an array that I need to convert into a CSV format with specific attributes. var data = [ { "Name":"nom1", "Division":"first", "Cities":['city1','c ...

What is the best way to transform a socket message into a JSON format using Python?

When a web request comes in, I receive a string with the code below: data_from_flask = c.recv(2048).decode('utf8') The message is displayed as: 'GET / HTTP/1.1\r\nHost: localhost:31477\r\nConnection: keep-alive\r&b ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

When executing store.sync() in ExtJS, all fields are passed

In the latest version of ExtJS (6.5.0), I have set up a Store and an editable grid panel: Ext.define('StateStore',{ extend: 'Ext.data.Store', alias: 'store.stateStore', storeId : 'StateStore', field ...

Utilizing d3.json: changing the URL with dynamic data

Just getting started with d3 and building a sankey diagram. I came across a sample that uses an external .json file with d3.v3, even though it is an outdated version. Since my tree also relies on this version, I'd like to stick to just one d3 version. ...

How do I set a new value for a variable from within a function?

After retrieving initial numbers from a JSON file, I want to update them using an ajax call. How do I go about replacing the values of homePoints and awayPoints with the new ones fetched through ajax? I have reviewed the provided answers but none seem to ...

Finding the position of a currently selected div by utilizing their data attributes

I am seeking to determine the index of an active div based on its data attributes. Currently, my approach involves obtaining the index on a sorted table. However, this method is ineffective in the case of an unsorted table: var count = $(".active").index ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...

Does the sequence matter when studying JavaScript, Ajax, jQuery, and JSON?

Expanding my job opportunities is a top priority for me, which is why I am dedicated to learning JavaScript, AJAX, jQuery, and JSON. As I delve into these languages, I can see how they all have roots in JavaScript. My main inquiry is about the relationsh ...

Displaying a webpage exclusively based on the user's origin from a particular page or link

Is there a way to restrict access to a web page so that it is only visible to users who come from a specific page or link? If the page's link is accessed directly from the browser or from any other source aside from the specified page or link, would i ...

What is the best way to show a table with 100% width in the Chrome browser?

I am currently working on debugging and expanding an express application that showcases a dataset through a series of nested tables on a webpage. Initially, all the CSS resided within style tags in the head section of the HTML file, and the tables were dis ...