Insert a fresh row into the current table

Is it possible to add a new row to an existing table in SAP UI5?

Below is the code snippet:

onInit: function() {
    var oModel = new sap.ui.model.json.JSONModel("Model/Clothing.json");
    this.getView().setModel(oModel);
    var table = this.getView().byId("tableid");
    table.bindItems("/catalog/clothing/categories", new sap.m.ColumnListItem({
      type: "Navigation",
      press: function(evt) {},
      cells: [
        new sap.m.Text({
          text: "{name}"
        }), new sap.m.Text({
          text: "{amount}"
        }), new sap.m.Text({
          text: "{currency}"
        }), new sap.m.Text({
          text: "{size}"
        })
      ]
    }));
    table.setModel(oModel);
  },
  onPress: function(oEvent) {
    var table = this.getView().byId("tableid");
    var items = table.getSelectedItems();
    for (var i = 0; i < items.length; i++) {
      var data = new sap.m.ColumnListItem({
        cells: [new sap.m.Text({
          text: "new Row1"
        }), new sap.m.Text({
          text: "new row1"
        }), new sap.m.Text({
          text: "new row1"
        }), new sap.m.Text({
          text: "new row1"
        })]
      });
      table.addItem(data);
    }
  },
<Table id="tableid" mode="MultiSelect" select="addRows">
  <columns>
    <Column>
      <Text text="column1" />
    </Column>
    <Column>
      <Text text="column2" />
    </Column>
    <Column>
      <Text text="column3" />
    </Column>
    <Column>
      <Text text="column4" />
    </Column>
  </columns>
</Table>
<Button text="Edit" press="onPress" />

See the output image here:

https://i.sstatic.net/8TId3.png

What I aim to do:

  1. Select a checkbox.
  2. Press the Edit button.
  3. When Edit is pressed, I want to insert a new row below the selected checkbox row.

Can this be achieved?

Please note the new row is currently being added at the end of the table

Answer №1

To place an item at a specific index, you can utilize the insertItem method.

This method requires two parameters: the item you wish to add and the index at which you want to insert it.

To determine the index where you want to add the new item, use the indexOfItem method, then add +1 to that index for the new item.

Check out this demo for a visual example.

Answer №2

When implementing data binding, it is recommended not to insert a new table row control. Instead, you should add a new entry to your model node:

UPDATE: revised solution below:

onPress : function(e) {
    var model   = this.getView().getModel();                                // accessing the model
    var rows    = model.getProperty("/catalog/clothing/categories");         // array containing all rows in the model
    var currentObj = e.getSource().getBindingContext().getObject();          // retrieving the current object
    var newItem = { name: null, amount: null, currency: null, size: null }  // new empty object

    var idx = $.map(rows, function(obj, index) {                            // obtaining the index of the selected item in the array
        if(obj === currentObj) {
            return index;
        }
    })

    rows.splice(idx, 0, newItem);                                           // inserting the new item at the index

    model.setProperty("/catalog/clothing/categories", rows);                // updating the model with the modified array
}

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

What is the most effective method for serializing SVG data from the client's Document Object Model (DOM

As I delve into the world of creating interactive SVG/AJAX interfaces, I find myself faced with a challenge. Users are constantly manipulating elements on-the-fly and I want to give them the option to export their current view as a PNG image or an SVG docu ...

Layered parallax scenery

I'm interested in creating a parallax effect similar to this example. https://medium.com/@PatrykZabielski/how-to-make-multi-layered-parallax-illustration-with-css-javascript-2b56883c3f27 However, I find the use of HAML and Coffeescript in the mentio ...

Outputting PHP variables in JavaScript is a common practice used to pass

I am struggling to use a variable in my JavaScript code. I have attempted a few methods but none seem to work. The variable I need to include in the JavaScript is option-<?php echo $option['product_option_id']; ?> Below is my current Java ...

Differentiate the items within a list containing identical divs using JavaScript

Currently, I am expanding my knowledge in HTML, CSS, and JS by incorporating Angular and JQuery. In one of my projects, there is a div labeled "eventBoxes" where multiple divs known as "eventBox" can be added. I have created a template for the eventBox i ...

Utilizing JavaScript: Storing the output of functions in variables

Currently in the process of learning JavaScript and aiming to grasp this concept. Analyzed the following code snippet: function multiNum(x, y){ return x * y; } var num = multiNum(3, 4); document.write(num); Decided to try it out on my own, here's ...

I'm having trouble finding the solution to setting a token in my request header

I have been following a tutorial in a book to build the authentication for my app. However, I am facing an issue where after logging in correctly, I am unable to set the token back into the request. The error message that I receive is: Failed to execute ...

Collapsing or expanding the Material UI accordion may lead to flickering on the page

import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Accordion from "@material-ui/core/Accordion"; import AccordionDetails from "@material-ui/core/AccordionDetails"; import Accordi ...

Linking a variable in typescript to a translation service

I am attempting to bind a TypeScript variable to the translate service in a similar way as binding in HTML markup, which is functioning correctly. Here's what I have attempted so far: ngOnInit() { this.customTranslateService.get("mainLayout.user ...

Viewing Server Logs in a Discord Channel

My gaming server stores logs in .txt format, and I'm looking for a way to automatically send updates to a Discord channel whenever there is new log data. I am currently developing a Discord bot using Node.js. Does anyone have any suggestions on how I ...

The mathematical logic behind navigating forward and backward in Angular

Calling all math experts! I need your help with a slider issue. The prevSlide function is working perfectly, but the nextSlide function seems to be starting off on the wrong foot. It goes 1-2-3 and then jumps to 2-3-2-3... It's definitely a math probl ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Displaying API response array object in React application

Currently, I am attempting to retrieve information from an API, parse the response content, and then display it in a loop. However, I have encountered a warning message: webpackHotDevClient.js:138 ./src/App.js Line 20: Expected an assignment or function ...

Show a particular attribute from an array

My goal is to create a function that displays only minivans from an array of cars when a button is pressed. However, I'm having trouble getting anything to display when the button is clicked, even though there are no errors in the program. Any advice ...

What is the best way to redirect users to the login page when they are logged out from a different tab or window?

Ensuring user authentication and managing inactivity are crucial components of my Nodejs application, where I leverage cookie-session and passport.js. app.use(require("cookie-session")({ secret:keys.session.secret, resave:false, saveUninitiali ...

Guide on importing an external JavaScript library in Node.js utilizing a TypeScript declaration file

I am working on a Node.js project using Typescript and I am facing an issue with integrating mime.js (https://github.com/broofa/node-mime). Even though I have a declaration file available (https://github.com/borisyankov/DefinitelyTyped/blob/master/mime/mim ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

How can I make arrays of a specific length and populate them in JavaScript?

For instance: I have over 100 locations in a single array, each with latitude and longitude values. I need to use these locations with the Google distance matrix API to find nearby shops for my users. The issue is that this API can only handle 25 destinat ...

Stop Bootstrap IE menu from closing when scrollbar is clicked

When using IE, the dropdown menu closes when clicking on the scrollbar. However, it functions properly when scrolling with the mouse wheel. To see the issue in action and potentially offer a solution, you can visit this Codeply link: I'm seeking sug ...

Move the absolute div by sliding it to the left from 120% to -10px

I want to move an absolute positioned div from the left side of the screen to -10px on button click. Here's my attempt so far, but it's not working as expected. Javascript/jQuery $('.button').click(function() { $(this).parent().f ...

What is the best way to handle reading hefty files using the fs.read method and a buffer in JavaScript?

I'm currently delving into the world of javascript, and one of my go-to exercises when learning a new programming language is to create a hex-dump program. The main requirements for this program are: 1. to read a file provided through the command line ...