SAPUI5: Refreshing table contents after oData.read - sapui5

Im building an application with two textboxes, a button and a table. On pressing the button, an array of filters is composed from the contents of the textboxes and sent to my oData service in a read request. Right now, when one record is returned (as it shows in the console), the table will not be updated. What am I missing?
This is the table:
<Table id="PLTab" items="{/ORDSET}">
<headerToolbar>
<Toolbar>
<Title text="Planned Orders" level="H2" />
</Toolbar>
</headerToolbar>
<columns>
<Column>
<Text text="Product" />
</Column>
<Column>
<Text text="Planned Order" />
</Column>
<Column>
<Text text="Production Planner" />
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<ObjectIdentifier title="{Maktx}" text="{Matnr}" />
<Text text="{Ordno}" />
<Text text="{Name}" />
</cells>
</ColumnListItem>
</items>
</Table>
And this is the relevant part of the controller:
onInit: function() {
var oModel = this.getOwnerComponent().getModel("path");
oModel.refresh(true);
this.getView().setModel(oModel);
},
openOrders: function(oEvent) {
var PLFilters = [];
PLFilters.push(new sap.ui.model.Filter({
path: "Matnr",
operator: sap.ui.model.FilterOperator.EQ,
value1: this.getView().byId("Product").getValue()
}));
PLFilters.push(new sap.ui.model.Filter({
path: "Locno",
operator: sap.ui.model.FilterOperator.EQ,
value1: this.getView().byId("Location").getValue()
}));
var oModel = this.getOwnerComponent().getModel("path");
oModel.read("/ORDSET", {
filters: PLFilters,
success: function(oData, oResponse) {
console.log(oData);
}
});
}
Thanks & regards,
Max

var oModel = this.getOwnerComponent().getModel("path");
You use the model named "path" to read data, but in your XML View you use the default model (unnamed).
Try to change to
var oModel = this.getOwnerComponent().getModel();

Related

suggestion to implement the Grouping, Filtering and Sorting of my table in sapui5

I am trying to implement Grouping, Filtering and Sorting on a table with which I bring some data.
I have been able to perform Grouping and Sorting without problems, but I have not been able to filter correctly.
This would be the code of the fragment that I used for Grouping, Filtering and Sorting:
<core:FragmentDefinition xmlns:core="sap.ui.core" xmlns="sap.m">
<ViewSettingsDialog confirm="onConfirm">
<sortItems>
<ViewSettingsItem selected="true" key="Xao" text="Tipo"/>
<ViewSettingsItem key="Xoccupant" text="Ocupante"/>
</sortItems>
<groupItems>
<ViewSettingsItem key="Xao" text="Tipo"/>
</groupItems>
<filterItems>
<ViewSettingsFilterItem key="Xao" text="Tipo" multiSelect="false" items="{/d/results/Xao}">
<items>
<ViewSettingsItem key="{Xao}" text="{Xao}"/>
</items>
</ViewSettingsFilterItem>
</filterItems>
</ViewSettingsDialog>
</core:FragmentDefinition>
On the part of the controller, this would be the code it occupies:
onPress: function () {
this._Dialog = sap.ui.xmlfragment("LogonPage.LogonPage.fragments.Dialog", this);
this._Dialog.open();
},
onClose: function () {
this._Dialog.close();
},
onTableSettings: function (oEvent) {
// Abra el cuadro de diálogo Configuración de tabla
this._oDialog = sap.ui.xmlfragment("LogonPage.LogonPage.fragments.SettingsDialog", this);
this._oDialog.open();
},
onConfirm: function (oEvent) {
var oView = this.getView();
var oTable = oView.byId("table0");
var mParams = oEvent.getParameters();
var oBinding = oTable.getBinding("items");
// apply grouping
var aSorters = [];
if (mParams.groupItem) {
var sPath = mParams.groupItem.getKey();
var bDescending = mParams.groupDescending;
var vGroup = function (oContext) {
var name = oContext.getProperty("Xao");
return {
key: name,
text: name
};
};
aSorters.push(new sap.ui.model.Sorter(sPath, bDescending, vGroup));
}
// apply sorter
var sPath = mParams.sortItem.getKey();
var bDescending = mParams.sortDescending;
aSorters.push(new sap.ui.model.Sorter(sPath, bDescending));
oBinding.sort(aSorters);
// apply filters
var aFilters = [];
var sQuery = oEvent.getParameter("query");
if (sQuery) {
aFilters.push(new Filter("Xao", FilterOperator.Contains, sQuery));
}
oBinding.filter(aFilters);
},
And this is the view of my table, what I want to filter is all that contains the Xao section of my table.
<Table inset="false" items="{/d/results}" id="table0" width="auto">
<items>
<ColumnListItem type="Active" id="item1">
<cells>
<Text text="{Xao}" id="text7"/>
<Text text="{Xoccupant}" id="text8"/>
<Text text="{ path: 'Validfrom', type: 'sap.ui.model.type.Date', formatOptions:
{ source: {
pattern: 'yyyyMMdd' },
pattern: 'dd/MM/yyyy' } }" id="text9"/>
<Text text="{ path: 'Validto', type: 'sap.ui.model.type.Date', formatOptions:
{ source: {
pattern: 'yyyyMMdd' }, pattern: 'dd/MM/yyyy' } }" id="text10"/>
</cells>
</ColumnListItem>
</items>
<columns>
<Column id="column0">
<header>
<Label text="Tipo" id="label0"/>
</header>
</Column>
<Column id="column1">
<header>
<Label text="Ocupante" id="label1"/>
</header>
</Column>
<Column id="column2">
<header>
<Label text="Fecha de Apartado" id="label2"/>
</header>
</Column>
<Column id="column3">
<header>
<Label text="Fecha de Finalización" id="label3"/>
</header>
</Column>
</columns>
</Table>
And here the code of the view, where I enable Grouping, Filtering and Sorting of my table
<headerToolbar>
<Toolbar id="toolbar3">
<Title text="Puestos de Trabajo"/>
<ToolbarSpacer/>
<Button press="onTableSettings" icon="sap-icon://drop-down-list" tooltip="Settings"/>
</Toolbar>
</headerToolbar>
Any ideas or suggestions to correctly filter my table?
Check your onConfirm function in the controller - the code for the filtering looks more like code for a search field. You have to process the filters coming from the event: https://sapui5.hana.ondemand.com/#/api/sap.m.ViewSettingsDialog%23events/confirm
For you this will contain only filters for your Xao field but my recommendatio is set a breakpoint in the function and analyse the oEvent.getParameters() structure.

How to Remove Row from Table

This question is a follow up to this: Button to add new row in SAPUI5 table
In my new scenario, I have added a "remove" button in the first column of the table. Again, the JSON file looks like this:
{
"Invoices": [
{
"ProductName": "Pineapple",
"Quantity": 21,
"ExtendedPrice": 87.2000,
"ShipperName": "Fun Inc.",
"ShippedDate": "2015-04-01T00:00:00",
"Status": "A"
},
...
]
}
My view now 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="Row" press="fetchRecords"/>
</Toolbar>
</headerToolbar>
<columns>
<Column width="50px"/>
<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>
<Button icon="sap-icon://delete" press="deleteRow" type="Reject"/>
<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>
And I have a function for adding a row (this one works fine):
addRow: function() {
this.getView().getModel("invoice").create("/Invoices", {
ProductName: "",
Quantity: "",
ShippedDate: "",
Status: ""
});
}
And I am trying to build one for deleting. This is what I have so far:
deleteRow: function(oArg) {
// var array = oArg.oSource.sId.split("-");
// var index = array[array.length - 1];
var path = oArg.oSource.oPropagatedProperties.oBindingContexts.invoice.sPath;
delete this.getView().getModel("invoice").oData[path.substr(1)];
this.getView().getModel("invoice").refresh(true);
}
But the row gets emptied and then returns again (like getting fetched from the mock server again). I am trying to completely remove the row (not just its contents), and the data to be removed.
I have seen plenty of examples online, but none cover my use case.
If you already use create for create new row then I think the best is to be consistent and use remove in order to remove it.
so in your case I think your code should look something like this:
this.getView().getModel("invoice").remove(path);
This line will do both:
Execute DELETE request to delete the object on the server (if you are using oDataModel)
Will delete the row from the table and refresh it because the table is bounded to this model
If you can please always use binding in your code. Using binding is much more efficient and easy to maintain because you don't need to deal with any DOM objects. The only thing that you need to do in code is creating/deleting/updating your model objects and UI5 runtime will do the rest for you.

sap ui5 with json data binding

If I have json data like this
[{"processor":"Mr. XYZ","components":["asd","efg","ghi","fjk"]} ,
{"processor":"Mr. XYZ","components":["asd","efg","ghi","ghi"]} ,
{"processor":"Mr. XYZ","components":["asd","efg","lkl"]} ]
If I am binding this to a table:
<Table id="myt1" items="{path: '/'}">
<columns>
<Column>
<Label text="Processor"/>
</Column>
<Column>
<Label text="Components"/>
</Column>
</columns>
<items>
<ColumnListItem>
<Text text="{processor}"/>
<Text text="{components}"/>
</ColumnListItem>
</items>
</Table>
How do I bind the array of components in separate lines in a cell for a processor in that table ?
Please refer the image for the output I am looking for.
Thanks in advance !
You could use a text formatter to add a new line after each array element.
<ColumnListItem>
<Text text="{processor}"/>
<Text text="{
path: 'components',
formatter: '.formatter.formatText'
}"/>
</ColumnListItem>
Formatter:
sap.ui.define([], function () {
"use strict";
return {
formatText : function(s){
var sOut = "";
s.forEach(function(sTxt){
sOut += sTxt + "\n";
});
return sOut;
}
}
});

SAPUI5 : JSONModel is not a constructor

I have an SAPUI5 app with 2 views. When I try navigate from the first view to the second view with an router it throws this error:
"Uncaught TypeError: JSONModel is not a constructor(…)"
The problem is I have to consume the content of the JSON to fill a table and with this error it is still empty
In a similar case/application my code runs without a problem, so I would be happy if someone can read my code if there are some errors...
Main.view.xml
<mvc:View controllerName="App.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
displayBlock="true" xmlns="sap.m">
<App>
<pages>
<Page>
<content>
<Table id="paramTable" items="{/callbackData}" width="auto" class="sapUiResponsiveMargin">
<columns>
<Column>
<Label text="Parameter"></Label>
</Column>
<Column width="10%">
<Label text="CurrentVal"></Label>
</Column>
<Column width="10%">
<Label text="TargetVal"></Label>
</Column>
<Column width="30%">
<Label text="Description"></Label>
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<ObjectIdentifier title="{key}"></ObjectIdentifier>
</cells>
<Text text="{currentVal}"></Text>
<Text text="{operator} {targetVal}"></Text>
</ColumnListItem>
</items>
</Table>
</content>
</Page>
</pages>
</App>
Main.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"
], function(Controller , JSONModel) {
"use strict";
return Controller.extend("App.controller.Main", {
onInit : function() {
this.getView().setModel(new JSONModel({
callbackData: []
}));
},
setTableData : function() {
var here = this;
$.ajax({
url : '../../test.xsjs',
type : "GET",
success : function(data) {
here.getView().getModel().setProperty("/callbackData", data);
}
});
}
});
});
Thanks in advance!!!
var oModel = new JSONModel({
callbackData: []
});
this.getView().setModel(oModel);

How can I get row value for each sap.m.select element

<m:Table id="tableId"
inset="false"
mode="MultiSelect"
width = "100%"
fixedLayout="false"
border-collapse="collapse"
items="{
path: 'jsonViewModel>/results',
sorter: {
path: 'ProductId'
}
}">
<columns>
<Column
minScreenWidth="Desktop"
demandPopin="true">
<Text text="Product No" />
</Column>
<Column
minScreenWidth="Desktop"
demandPopin="true"
hAlign="Left">
<Text text="Model" />
</Column>...
</columns>
<items>
<ColumnListItem>
<cells>
<ObjectIdentifier
title="{jsonViewModel>ProductId}"/>
<Select id="selectId"
items="{
path: '/ModelList',
sorter: { path: 'Name' }
}">
<core:Item key="{modelId}" text="{Name}" />
</Select>...
</cells>
</ColumnListItem>
</items>
</Table>
First I have a jsonViewModel which is holding Products JSON array and also there is a ModelList service which gives me the list of models. So I should be able to fill some inputs(I didn't show other inputs cause I can retrive their values) and select model of products. But if I have 5 products I also have 5 select elements and I can't retrieve the select item for each rows(for each products). For example I can't retrieve the value with these codes in controller:
var oSelect = this.getView().byId("selectId");
var selectedItemObject = oSelect.getSelectedItem().getBindingContext().getObject();
var selectedModelName = selectedItemObject.Name;
Cause I have 5 select elements indeed and with these codes I can't retrieve every selected item object. Any help would be appreciated.
Cant we go through every row and then fetch the select control and then fetch the selectedItem? I mean,
var aItems = this.getView().byId("tableId").getItems();
for(var i =0;i<aItems.length;i++){
var aCells = aItems[i].getCells();
// I know select is at 0th cell, so I can use aCells[0].
var rowSelectedKey = aCells[0].getSelectedItem().getKey();
// once you have the selcetedKey, you can save them in a local array or // model and after the loop, you can work with them
}