How to bind data from controller to Xml View table - sapui5

I am having a table with columns as below:
<Table id="table2" visibleRowCount="5" rows="{
path: '/ProductCollection',
sorter: {path: 'serialId', descending: false}}">
<columns>
<Column width="50px">
<m:Text text="Employee ID" />
<template>
<m:Text text="{employeeId}" wrapping="false" />
</template>
</Column>
<Column width="200px">
<m:Text text="EmployeeName" />
<template>
<m:Text text="{employeeName}" wrapping="false" />
</template>
</Column>
</columns>
</Table>
And JSON Data is :
var oData = {
ProductCollection: [
{
employeeId: "1"
employeeName:"xyz"
},
{
employeeId: "1"
employeeName:"xyz"
},
{
employeeId: "1"
employeeName:"xyz"
}
]
};
And i have tried binding as :
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(ProductCollection);
this.getView().setModel(oModel);
I am getting the data but into model but unable to display values in table getting empty rows.I am facing problem in binding(xml view)any guiding links or a solution would be much helpful , TIA

<mvc:View controllerName="reg.cmdd.Consumer.controller.Home" xmlns="sap.ui.table" xmlns:mvc="sap.ui.core.mvc" xmlns:u="sap.ui.unified"
xmlns:c="sap.ui.core" xmlns:m="sap.m" height="100%">
<m:Page showHeader="false" enableScrolling="false" class="sapUiContentPadding">
<m:content>
<Table id="table2" visibleRowCount="5" rows="{ path: '/ProductCollection', sorter: {path: 'serialId', descending: false}}">
<columns>
<Column width="50px">
<m:Text text="Employee ID"/>
<template>
<m:Text text="{employeeId}" wrapping="false"/>
</template>
</Column>
<Column width="200px">
<m:Text text="EmployeeName"/>
<template>
<m:Text text="{employeeName}" wrapping="false"/>
</template>
</Column>
</columns>
</Table>
</m:content>
</m:Page>
</mvc:View>
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("reg.cmdd.Consumer.controller.Home", {
onInit: function () {
var oData = {
ProductCollection: [{
employeeId: "1",
employeeName: "xyz"
}, {
employeeId: "1",
employeeName: "xyz"
}, {
employeeId: "1",
employeeName: "xyz"
}
]
};
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(oData);
this.getView().setModel(oModel);
}
});
});
Your code is fine, the problem must be elsewhere
EDIT:
check this line:
oModel.setData(ProductCollection);
it should be
oModel.setData(oData);

Related

How to remove the space between bar and legend in a sapui5 StackedBarChart

I like to create a barchart and have gotten pretty far.
My chart is a standalone view and next to some other views inside of a Shell>App>Page
View.view.xml:
<mvc:View
controllerName="my.controller.Chart"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
xmlns:viz="sap.viz.ui5.controls"
xmlns:vizData="sap.viz.ui5.data"
xmlns:vizFeeds="sap.viz.ui5.controls.common.feeds"
displayBlock="true"
height="100%"
busyIndicatorDelay="0"
class="myChartView"
>
<Panel
headerText="Chart"
class="sapUiResponsiveMargin"
width="auto"
>
<viz:VizFrame
vizType="100_stacked_bar"
id="idDualStackedChart"
width="100%"
class="myStackedBarChart"
vizProperties="{plotArea: {
dataLabel:{
visible: true
},
colorPalette: ['#009c00','#ff0000'],
gridline: {
visible: false
}
},
interaction: {
noninteractiveMode: true
},
title:{ visible: false, text:'Auslastung'},
categoryAxis: {visible: false},
valueAxis: {visible: false},
legendGroup: {
layout: {
position: 'bottom',
alignment: 'center'
}
}
}"
>
<viz:dataset>
<vizData:FlattenedDataset data="{/items}">
<vizData:dimensions>
<vizData:DimensionDefinition
name="Maschine"
value="{Machine}"
/>
</vizData:dimensions>
<vizData:measures>
<vizData:MeasureDefinition
name="Stopped"
value="{Stopped}"
/>
<vizData:MeasureDefinition
name="Running"
value="{Running}"
/>
</vizData:measures>
</vizData:FlattenedDataset>
</viz:dataset>
<viz:feeds>
<vizFeeds:FeedItem
uid="valueAxis"
type="Measure"
values="Running,Stopped"
/>
<vizFeeds:FeedItem
uid="categoryAxis"
type="Dimension"
values="Maschine"
/>
</viz:feeds>
</viz:VizFrame>
</Panel>
</mvc:View>
Chart.controller.ts
import Controller from "sap/ui/core/mvc/Controller";
import JSONModel from "sap/ui/model/json/JSONModel";
export default class ChartController extends Controller {
onInit() {
const oSampleData = new JSONModel("model/Data.json");
this.getView().setModel(oSampleData);
const chartFrame = this.byId("idDualStackedChart");
console.log(chartFrame);
}
}
Data.json
{
"items": [
{
"Machine": "Q1",
"Stopped": "20",
"Running": "40"
}
]
}
The only problem I have is: There is a lot of space above the chart and a lot of space between the chart-bar and the legend.
How can I decrease/remove this space?

How to edit a row using dialogue box

I have created a sap ui5 table with 5 columns where One of the column of table will have a button with edit icon.
I have tried as below:
<Table id="table2" visibleRowCount="5" rows="{
path: '/ProductCollection',
sorter: {path: 'serialId', descending: false}
}">
<columns>
<Column width="50px">
<m:Text text="S.No" />
<template>
<m:Text text="{serialId}" wrapping="false" />
</template>
</Column>
<Column width="200px">
<m:Text text="EmployeeName" />
<template>
<m:Text text="{employeeName}" wrapping="false" />
</template>
</Column>
<Column width="200px">
<m:Text text="EmployeeId" />
<template>
<m:Text text="{employeeId}" wrapping="false" />
</template>
</Column>
<Column width="200px">
<m:Text text="Age" />
<template>
<m:Text text="{age}" wrapping="false" />
</template>
</Column>
<Column width="200px">
<m:Text text="Email" />
<template>
<m:Text text="{email}" wrapping="false" />
</template>
</Column>
<Column hAlign="End" width="4rem" >
<m:Text text="Edit" />
<template>
<m:Button icon="sap-icon://edit" press="editRow" type="Reject"/>
</template>
</Column>
</columns>
<dragDropConfig>
<dnd:DropInfo
groupName="moveToTable2"
targetAggregation="rows"
dropPosition="Between"
drop="onDropTable2" />
<dnd:DragDropInfo
sourceAggregation="rows"
targetAggregation="rows"
dropPosition="Between"
dragStart="onDragStart"
drop="onDropTable2" />
</dragDropConfig>
</Table>
On click of the edit button, a dialog box should open along with the data of the clicked row.
I have tried editing the row with the below function
where I am opening a dialog box with the current values , so that update on click of OK.
And this is my controller:
editRow: function(oEvent) {
var oControl = oEvent.getSource();
var oItemPath = oControl.getBindingContext().getPath();
var oObject = this.byId("table2").getModel() .getProperty(oItemPath);
var editRecord = oEvent .getSource().getBindingContext() .getObject();
var editRecordRank = editRecord.Rank;
var oDialog1 = new Dialog({
title: "Wafer",
contentWidth: "40px",
contentHeight: "300px",
content: [
new sap.m.Text({
width: "100%",
text: "EMPid"
}),
new sap.m.FlexBox({
justifyContent: "Center",
items: [
new sap.m.Select("EmployeeEditId", {
width: "60%",
items: [
new sap.ui.core.Item("itemee11", { text: "33" }),
new sap.ui.core.Item("iteme12", {
text: "78"
}),
new sap.ui.core.Item("itemee13", {
text: "100"
}),
new sap.ui.core.Item("iteme14", {
text: "75"
}),
new sap.ui.core.Item("iteme15", {
text: "101"
})
]
})
]
}),
new sap.m.Text({ width: "100%", text: "EMPname" }),
new sap.m.FlexBox({
justifyContent: "Center",
items: [
new sap.m.Select("EmployeeNameEditId", {
width: "60%",
items: [
new sap.ui.core.Item("iteme1111", {
text: "test1"
}),
new sap.ui.core.Item("iteme1234", {
text: "test2"
}),
new sap.ui.core.Item("iteme1312", {
text: "test3"
})
]
})
]
}),
new sap.m.Text({ width: "100%", text: "age" }),
new sap.m.FlexBox({
justifyContent: "Center",
items: [
new sap.m.Select("AgeEditId", {
width: "60%",
items: [
new sap.ui.core.Item("iteme15211", { text: "22" }),
new sap.ui.core.Item("iteme136454", { text: "23" }),
new sap.ui.core.Item("iteme213754", { text: "33" }),
]
})
]
}),
new sap.m.Text({ width: "100%", text: "Email" }),
new sap.m.FlexBox({
justifyContent: "Center",
items: [
new sap.m.Select("EmailEditId", {
width: "60%",
items: [
new sap.ui.core.Item("iteme11411", { text: "a#gmail.com" }),
new sap.ui.core.Item("iteme34", { text: "b#hotmail.com" }),
new sap.ui.core.Item("iteme314", { text: "c#hotmail.com" })
]
})
]
})
],
beginButton: new Button({
type: ButtonType.Emphasized,
text: "Update",
press: function() {
var otab = this.byId("table2");
var rows = otab.getRows();
var rowsLength = otab.getBinding('rows').getLength();
var tableArr = [];
for ( var i = 0; i < rowsLength; i++ ) {
tableArr.push({
empId : rows[i].getCells()[0].getText(),
employeeName : rows[i].getCells()[1].getText(),
age: rows[i].getCells()[2].getText(),
email : rows[i].getCells()[3].getText(),
});
}
var employeeId= sap.ui.getCore().byId("empId ");
var empnameId = sap.ui.getCore().byId("employeeName ");
var ageId = sap.ui.getCore().byId("age");
var emailId = sap.ui .getCore().byId("email");
// data=oEvent.getSource
var componentText =empId.mAssociations.selectedItem;
var categoryText = empnameId.mAssociations.selectedItem;
var quantityText = ageId.mAssociations.selectedItem;
var mainCategoryText = emailId.mAssociations.selectedItem;
var cValue = sap.ui.getCore().byId(componentText) .mProperties.text;
var catValue = sap.ui.getCore().byId(categoryText).mProperties.text;
var qValue = sap.ui.getCore().byId(quantityText).mProperties.text;
var mValue = sap.ui.getCore().byId(mainCategoryText) .mProperties.text;
tableArr.map(function(item) {
if (item.empId==cValue){
item.empnameId = catValue;
item.ageId = qValue;
item.emailId = mValue;
}
return item; });
// var aContexts = sap.ui.getCore().byId("test");
var oModel = new sap.ui.model.json.JSONModel();
var oTable = this.byId("table2");
oModel.setData({ modelData: tableArr });
oTable.setModel(oModel);
oTable.bindRows("/modelData");
oDialog1.close();
}.bind(this)
}),
endButton: new Button({
text: "Close",
press: function() {
this.pressDialog.close();
}.bind(this)
})
});
oDialog1.open();
},
any guiding links or a solution would be much helpful , TIA
The binding for the dialog is missing. Add the dialog as "dependent" on the view to be connected to the view’s model lifecycle. Or try to bind the element like this oDialog.bindElement(sPath).
Try sth. like oDialog1.bindElement(oItemPath) before opening the dialog.

SAPUI5 onSearch() Filter update

Somehow my filter update through the function onSearch is not updating the view. The initial Filter in the XML View is working fine. Also when sIaNr is empty the aFilter = [] is working as I'm seeing all results. But when sIaNr is not empty this part is called and the filter is not working:
aFilter.push(new Filter("raufnr", FilterOperator.EQ, sIaNr))
this is my Code
ZCATS_TESTJ.json
{
"d": {
"results": [{
"status": "30",
"skostl": "0001",
"catshours": "2.50",
"ktext": "test1",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "xx123",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025"
}, {
"status": "30",
"skostl": "0001",
"catshours": "8.00",
"ktext": "test2",
"counter": "000002919281",
"mandt": "101",
"pernr": "1234",
"usrid": "xx123",
"workdate": "\/Date(1441065600000)\/",
"raufnr": "0815"
}, {
"status": "30",
"skostl": "0001",
"catshours": "8.00",
"ktext": "test1",
"counter": "000002919281",
"mandt": "101",
"pernr": "00015822",
"usrid": "xx123",
"workdate": "\/Date(1441065600000)\/",
"raufnr": "6000007"
}]
}
}
List.view
<mvc:View
controllerName="sap.ui.bookedTimes.wt.controller.List"
id="listview"
xmlns:l="sap.ui.layout"
xmlns:mvc="sap.ui.core.mvc"
xmlns:fb="sap.ui.comp.filterbar"
xmlns:core="sap.ui.core"
xmlns="sap.m">
<Table id="exportTable" inset="false" growing="true" growingThreshold="700" visible="true"
items="{
path : 'view>/d/results',
filters : [
{ path : 'raufnr', operator : 'EQ', value1 : '6000007'}
]
}">
<headerToolbar>
<OverflowToolbar>
<ToolbarSpacer />
<Button icon="sap-icon://excel-attachment" press="onExport"/>
</OverflowToolbar>
</headerToolbar>
<columns>
<Column>
<Text text="IA-Nummer" />
</Column>
<Column>
<Text text="Bezeichnung" />
</Column>
<Column>
<Text text="Datum" />
</Column>
<Column hAlign="End">
<Text text="Zeit" />
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<ObjectIdentifier title="{view>raufnr}" />
<Text id="tText" text="{view>ktext}" />
<Text text="{path: 'view>workdate', type: 'sap.ui.model.type.Date', formatOptions: { pattern: 'dd.MM.yyyy' } }" />
<Text text="{view>catshours}" />
</cells>
</ColumnListItem>
</items>
</Table>
List.controller
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel',
'sap/ui/core/util/MockServer',
"sap/ui/model/Filter",
"sap/ui/model/FilterOperator",
"sap/ui/model/FilterType"
// 'sap/ui/export/Spreadsheet'
], function(jQuery, Controller, JSONModel, Filter, FilterOperator, FilterType) {
"use strict";
return Controller.extend("sap.ui.bookedTimes.wt.controller.List", {
onInit : function () {
//Get Model
var jModel = this.getOwnerComponent().getModel("zCatsTestJ");
var that = this;
//after Model is loaded transform Date
jModel.attachRequestCompleted(function() {
//var oViewModel= new JSONModel(jModel);
for (var i = 0; i< jModel.oData.d.results.length; i++){
var sJsonDate = jModel.getProperty("/d/results/" + [i] + "/workdate");
//Json Date in Datumsformat umwandeln
var sNumber = sJsonDate.replace(/[^0-9]+/g,'');
var iNumber = sNumber * 1; //trick seventeen
var oDate = new Date(iNumber);
jModel.setProperty("/d/results/" + [i] + "/workdate", oDate);
}
//update the model with new Date format
that.getView().setModel(jModel, "view");
});
},
onSearch: function(oEvent) {
// build filter array
var aFilter = [];
var oParams = oEvent.getParameter("selectionSet");
var sIaNr = oParams[0].getValue();
var oList = this.getView().byId("exportTable");
var oBinding = oList.getBinding("items");
if (sIaNr) {
aFilter.push(new Filter("raufnr", FilterOperator.EQ, sIaNr));
}
//filter binding
oBinding.filter(aFilter, FilterType.Application);
}
});
});
any help would be greatly appreciated. Thanks
Delete 'sap/ui/core/util/MockServer' in the define part.

Data Not Visible in Second View

I am facing one issue with data not being visible in my project.
I have created two views: Input.view.xml and plant.view.xml. In my first view, I have a button as "Material Details" and on clicking that, it moves to second view. However, it is coming blank.
My JSON file is having all the data but it's not coming in second view.
Can you please suggest what is the issue and how to fix it?
"Input View" (First View)
<mvc:View
controllerName="stock.controller.main"
xmlns:l="sap.ui.layout"
xmlns:mvc="sap.ui.core.mvc"
xmlns:viz="sap.viz.ui5.controls"
xmlns="sap.m">
<App id="app">
<l:VerticalLayout
class="sapUiContentPadding"
width="100%"
height="100%">
<Label
text="Product"
labelFor="productInput" />
<Input id="productInput"
placeholder="Enter Material ..."
showSuggestion="true"
showTableSuggestionValueHelp="false"
suggestionRows="{/ProductCollection}"
suggestionItemSelected="onSelectItem">
<suggestionColumns>
<Column
hAlign="Begin"
popinDisplay="Inline"
demandPopin="true">
<Label text="Name"/>
</Column>
</suggestionColumns>
<suggestionRows>
<ColumnListItem>
<Label id="inputKey" text="{ProductId} {Name}"/>
</ColumnListItem>
</suggestionRows>
</Input>
<Button id="onDisplay"
text="{i18n>materialDetails}"
press="onDisplayPlant"
class="sapUiTinyMarginEnd" />
</l:VerticalLayout>
</App>
</mvc:View>
plant.view.xml (Second View)
<mvc:View
controllerName="stock.controller.plant"
xmlns="sap.m"
xmlns:viz="sap.viz.ui5.controls"
xmlns:l="sap.ui.layout"
xmlns:mvc="sap.ui.core.mvc">
<MessagePage
showNavButton="true"
navButtonPress="onNavBack"/>
<Table id="idProductsTable"
inset="false"
items="{
path: '/ProductCollection',
sorter: {
path: 'Name'
}
}">
<headerToolbar>
<Toolbar>
<Title text="Products" level="H2" />
</Toolbar>
</headerToolbar>
<columns>
<Column width="12em">
<Text text="Product" />
</Column>
<Column
minScreenWidth="Tablet"
demandPopin="true">
<Text text="Supplier" />
</Column>
<Column
minScreenWidth="Tablet"
demandPopin="true"
hAlign="End">
<Text text="Dimensions" />
</Column>
<Column
minScreenWidth="Tablet"
demandPopin="true"
hAlign="Center">
<Text text="Weight" />
</Column>
<Column hAlign="End">
<Text text="Price" />
</Column>
</columns>
<items>
<ColumnListItem>
<ObjectIdentifier
title="{Name}"
text="{ProductId}"/>
<Text text="{SupplierName}" />
<Text text="{Width} x {Depth} x {Height} {DimUnit}" />
<ObjectNumber
number="{WeightMeasure}"
unit="{WeightUnit}"
state="{
parts: [
{path: 'WeightMeasure'},
{path: 'WeightUnit'}
],
formatter: 'stock.Formatter.weightState'
}" />
<ObjectNumber
number="{
parts: [{
path: 'Price'
}, {
path: 'CurrencyCode'
}],
type: 'sap.ui.model.type.Currency',
formatOptions: {
showMeasure: false
}
}"
unit="{CurrencyCode}" />
</ColumnListItem>
</items>
</Table>
</MessagePage>
</mvc:View>
plant.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller",
"jquery.sap.global",
"stock/Formatter",
"sap/ui/core/routing/History",
"sap/ui/model/json/JSONModel"
], function (Controller, jQuery, Formatter, History,JSONModel) {
"use strict";
var TableController = Controller.extend("stock.controller.plant", {
onInit: function () {
var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json"));
this.getView().setModel(oModel);
},
getRouter : function () {
return sap.ui.core.UIComponent.getRouterFor(this);
},
onNavBack: function () {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
this.getRouter().navTo("input", {}, true);
}
}
});
return TableController;
});
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/core/mvc/XMLView",
"sap/ui/model/json/JSONModel"
], function(UIComponent, JSONModel, XMLView) {
"use strict";
var Component = UIComponent.extend("stock.Component", {
metadata: {
manifest: "json",
getTable: function () {
return this._rootView.getContent()[0];
}
},
publicMethods: [
"getTable"
],
dependencies: {
libs: [
"sap.m",
"sap.ui.layout"
]
},
rootView: "stock.view.input",
config: {
sample: {
files: [
"view.input.view.xml",
"controller.main.controller.js",
"Formatter.js"
],
description : "In this example assisted input is provided with table-like suggestions where several columns can display more details."
}
},
init : function () {
UIComponent.prototype.init.apply(this, arguments);
this.getRouter().initialize();
}
});
Component.prototype.createContent = function () {
this._rootView = sap.ui.xmlview({ viewName : "stock.view.plant" });
return this._rootView;
};
return Component;
});

JSBin: How to create demo example's of sapui5?

I want share working live example of SAPUI5 on stackoverflow, but I don't know how to create the JSBin example or which things we have to add or is there any simple way to create demo example of JSBin.
Or, you can create a Stack Snippet which is runnable by clicking the blue 'Run Code Snippet' button:
sap.ui.controller("view1.initial", {
onInit : function(oEvent) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
rows : [
{ value : "sap-icon://syringe", col2 : "Value 2", col3 : "Value 3", ol4 : "Value 4" },
{ value : "sap-icon://account", col2 : "Value 10", col3 : "Value 11", col4 : "Value 12" },
{ value : "sap-icon://chalkboard", col2 : "Value 14", col3 : "Value 15", col4 : "Value 16" },
{ value : "sap-icon://e-care", col2 : "Value 18", col3 : "Value 19", col4 : "Value 20" }
]
});
this.getView().setModel(oModel);
}
});
sap.ui.xmlview("main", {
viewContent: jQuery("#view1").html()
})
.placeAt("uiArea");
/* extra CSS classes here */
<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-xx-bindingSyntax="complex"
data-sap-ui-libs="sap.m"></script>
<div id="uiArea"></div>
<script id="view1" type="ui5/xmlview">
<mvc:View controllerName="view1.initial" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc">
<Table items="{/rows}">
<columns>
<Column>
<Text text="Col1" />
</Column>
<Column>
<Text text="Col2" />
</Column>
<Column>
<Text text="Col3" />
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<core:Icon src="{value}" />
<Text text="{col2}" />
<Text text="{col3}" />
</cells>
</ColumnListItem>
</items>
</Table>
</mvc:View>
</script>
You will need bootstrap script, View which will be in HTML tab only and its Controller under Javascript tab.
You can save this as your template after logging in and use it as starting point for your expamples.