Add a New Item to a Table / List

  1. Bind the collection of data to the <items> aggregation of table.
  2. Add a new entry to the model (instead of to the UI directly) when the user clicks on Add.

Thanks to the aggregation binding, UI5 will create a new ColumnListItem for you and you did not break the MVC pattern. Here are some examples, using..:

v2.ODataModel

v4.ODataModel

JSONModel

globalThis.onUI5Init = () => sap.ui.require([
  "sap/ui/core/mvc/XMLView",
  "sap/ui/model/json/JSONModel",
], async (XMLView, JSONModel) => {
  "use strict";
  const control = await XMLView.create({
    definition: document.getElementById("myxmlview").textContent,
    models: new JSONModel({
      myArray: [],
    }),
  });
  control.placeAt("content");
});

function onAddItemPress(event) {
  const model = event.getSource().getModel();
  const newArray = model.getProperty("/myArray").concat({
    id: globalThis.crypto.randomUUID(),
    text: "My New Item",
  });
  model.setProperty("/myArray", newArray, null, true);
}
html, body { height: 100%; }
body { margin: 0; }
<script defer id="sap-ui-bootstrap"
  src="https://sdk.openui5.org/resources/sap-ui-core.js"
  data-sap-ui-oninit="onUI5Init"
  data-sap-ui-libs="sap.ui.core,sap.m"
  data-sap-ui-theme="sap_horizon"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-excludejquerycompat="true"
  data-sap-ui-xx-waitfortheme="init"
></script>
<script id="myxmlview" type="text/xml">
  <mvc:View xmlns:mvc="sap.ui.core.mvc" height="100%" displayBlock="true">
    <Page xmlns="sap.m" title="My Items ({= ${/myArray}.length})">
      <headerContent>
        <Button text="Add" type="Emphasized" press="onAddItemPress" />
      </headerContent>
      <Table xmlns="sap.m"
        growing="true"
        items="{
          path: '/myArray',
          templateShareable: false,
          key: 'id'
        }">
        <columns>
          <Column>
            <Text text="UUID" />
          </Column>
          <Column>
            <Text text="Text" />
          </Column>
        </columns>
        <ColumnListItem>
          <Text text="{id}" />
          <Text text="{text}" />
        </ColumnListItem>
      </Table>
    </Page>
  </mvc:View>
</script>
<body id="content" class="sapUiBody sapUiSizeCompact">
</body>

For client-side models such as JSONModel, calling setProperty is sufficient. DO NOT use push or modify the internal model reference directly.

Leave a Comment