bind entity to get single record [duplicate] - sapui5

This question already has answers here:
bindProperty to Single OData Entity
(2 answers)
Closed 18 days ago.
How to fetch single entity record data please find the code below
binding in xml table.am doing like below
table in xml view
<Table items="{/dum}" id="table" width="auto">
When you can bind the url directly to the table:
If I give like below am getting all records.
var url = "/myentity";
var table = oView.byId("table");
table.bindItems({
path: url,
template: table.getBindingInfo("items").template
});
If I give var url = "/myentity('srujan')";
am not able to get particular user data
HTTP request failed400,Bad Request,{"error":{"code":"005056A509B11EE1B9A8FEC11C23378E","message":{"lang":"en","value":"System query options '$orderby,$skip,$top,$skiptoken,$inlinecount' are not allowed in the requested URI"

Here's the snippet that shows how bindElement ("binding" in the XML) it works for your case:
var oModel = new sap.ui.model.json.JSONModel({
"Product(1)": {
Price: 100,
Name: "Product # 1"
},
Products: [{
Price: 200,
Name: "Product # 1"
}, {
Price: 500,
Name: "Product # 2"
}, {
Price: 542,
Name: "Product # 3"
}]
});
sap.ui.getCore().setModel(oModel);
sap.ui.xmlfragment({
fragmentContent: document.getElementById("table").textContent
}).placeAt("content");
<!DOCTYPE html>
<html>
<body>
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script id="table" type="sapui5/xml">
<Table xmlns="sap.m" binding="{/Product(1)}">
<columns>
<Column>
<Label text="Binding" />
</Column>
<Column>
<Label text="Column 2" />
</Column>
<Column>
<Label text="Column 3" />
</Column>
</columns>
<items>
<ColumnListItem>
<Text text="/Products(1) on table" />
<Text text="{Name}" />
<Text text="{Price}" />
</ColumnListItem>
<ColumnListItem binding="{/Products/2}">
<Text text="/Products/2 on item" />
<Text text="{Name}" />
<Text text="{Price}" />
</ColumnListItem>
</items>
</Table>
</script>
<div id="content"></div>
</body>
</html>

Related

Table grouping resets selected values when adding new item

Here we have a very basic table with an Add button and grouping activated. When I select values for the existing items and then press the button to add a new row, my selected values are getting reset, but without grouping it works fine. Am I doing something wrong or is this a bug?
sap.ui.getCore().attachInit(() => sap.ui.require([
"sap/ui/core/mvc/XMLView",
"sap/ui/model/json/JSONModel" // sample model. Can be also an ODataModel.
], async (XMLView, JSONModel) => {
"use strict";
const control = await XMLView.create({
definition: `<mvc:View xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc">
<Table items="{
path: '/tableItems',
sorter: { path : 'group', group: true }
}">
<headerToolbar>
<OverflowToolbar>
<Title text="Test Table" />
<ToolbarSpacer/>
<Button id="addButton" text="Add" type="Emphasized" />
</OverflowToolbar>
</headerToolbar>
<columns>
<Column width="20rem">
<Label text="col0"/>
</Column>
<Column width="20rem">
<Label text="col1"/>
</Column>
</columns>
<ColumnListItem vAlign="Middle">
<Text text="{text}" />
<Select forceSelection="false" width="100%" xmlns:core="sap.ui.core">
<core:Item text="test1" key="test1" />
<core:Item text="test2" key="test2" />
<core:Item text="test3" key="test3" />
<core:Item text="test4" key="test4" />
</Select>
</ColumnListItem>
</Table>
</mvc:View>`,
afterInit: function() {
this.byId("addButton").attachPress(onPressAdd, this);
function onPressAdd() {
const oModel = this.getModel();
const aItems = oModel.getProperty("/tableItems");
const newItems = aItems.concat({
group: "3",
text: "3-1",
key: "3-1",
});
oModel.setProperty("/tableItems", newItems);
}
},
models: new JSONModel({
number: 0,
tableItems: [
{
group: "1",
text: "1-1",
key: "1-1",
},
{
group: "1",
text: "1-2",
key: "1-2",
},
{
group: "2",
text: "2-1",
key: "2-1",
},
{
group: "2",
text: "2-2",
key: "2-2",
},
],
}),
});
control.placeAt("content");
}));
<script id="sap-ui-bootstrap"
src="https://openui5.hana.ondemand.com/1.82.2/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core,sap.m"
data-sap-ui-theme="sap_fiori_3"
data-sap-ui-compatversion="edge"
data-sap-ui-async="true"
data-sap-ui-excludejquerycompat="true"
data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>
Set the growing="true" to the sap.m.Table.
This enables GrowingEnablement internally which prevents rerendering the entire ListBase (Table) when the target gets invalidated. Only the necessary item will be then appended to the table.
Generally, in order to optimize the rendering behavior, it's always a good practice to..:
Enable the growing property if the table / list is editable, shrinkable, or expandable.
Add key: <propertyName with unique values> to the ListBinding info object to benefit from the Extended Change Detection if the model is a client-side model such as JSONModel. With an ODataModel, the key is automatically added by the framework.
<Table xmlns="sap.m"
growing="true"
items="{
path: 'myModel>/myCollection',
key: <propertyName>, (if 'myModel' is not an ODataModel)
sorter: ...
}"
>

How can I bind a single property of my OData service to a Form?

Will you please tell me how to refer to the first tabular (and single) record?
There is a table with only one record:
<Table items="{WaybillsPlaces}" mode="SingleSelectMaster">
<columns>
<Column hAlign="Center">
<header>
<Text text="Number" />
</header>
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{CoNumber}" />
</cells>
</ColumnListItem>
</items>
</Table>
How can I read the field of the first record without a table?
<Text text="{WaybillsPlaces[0]/>CoNumber}"/>
I get a table reply, but I do not want to display it in the table - I want to display it in the form in text boxes, so there will always be one line in the response.
<entry>
<id>
http://xxxxx.xxx.local:8000/sap/opu/odata/sap/LOGISTICS_SRV/WaybillsPlaces('4610103052')
</id>
<title type="text">WaybillsPlaces('4610103052')</title>
<updated></updated>
<content type="application/xml">
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<d:CoNumber>46101030520001</d:CoNumber>
</m:properties>
</content>
</entry>
EDIT (As #Denis description in the comments):
I have an OData giving me the following entry
<entry>
<id>
http://xxxxx.xxx.local:8000/sap/opu/odata/sap/LOGISTICS_SRV/WaybillsPlaces('4610103052')
</id>
<title type="text">WaybillsPlaces('4610103052')</title>
<updated></updated>
<content type="application/xml">
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<d:CoNumber>46101030520001</d:CoNumber>
</m:properties>
</content>
</entry>
How can I bind the CoNumber property with a Input within a From ??
give and ID to your table, get the table in your controller and call its 'getItems()' method. Then get the first object in the returned array:
In your view
<Table id="myTable" items="{WaybillsPlaces}" mode="SingleSelectMaster">
<columns>
<Column hAlign="Center">
<header>
<Text text="Number" />
</header>
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{CoNumber}" />
</cells>
</ColumnListItem>
</items>
</Table>
In your controller
onCertainEvent(evt){
var oTable = this.getView().byId('myTable');
var oFirstItem = oTable.getItems()[0]; // This is your ColumnListItem object in the first row
var oFirstCellItem = oFirstItem.getCells()[0]; // This is your Text object in the first cell of the first row
var sCellText = oFirstCellItem.getText(); // This is the text string in your first cell of the first row
}
EDIT: bind only the first item in your model
In this case you can do aggregation binding. For aggregation binding you need multiplicity greater than 1. So do property binding in yout ColumnListItem with WaybillsPlaces/0/CoNumber
<Table id="myTable" mode="SingleSelectMaster">
<columns>
<Column hAlign="Center">
<header>
<Text text="Number" />
</header>
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{WaybillsPlaces/0/CoNumber}" />
</cells>
</ColumnListItem>
</items>
</Table>
EDIT: Data Binding options in certain events
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta charset="utf-8">
<title>MVC with XmlView</title>
<!-- Load UI5, select "blue crystal" theme and the "sap.m" control library -->
<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-libs='sap.m'
data-sap-ui-xx-bindingSyntax='complex'></script>
<!-- DEFINE RE-USE COMPONENTS - NORMALLY DONE IN SEPARATE FILES -->
<!-- define a new (simple) View type as an XmlView
- using data binding for the Button text
- binding a controller method to the Button's "press" event
- also mixing in some plain HTML
note: typically this would be a standalone file -->
<script id="view1" type="sapui5/xmlview">
<mvc:View
controllerName="my.own.controller"
xmlns:l="sap.ui.layout"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns:f="sap.ui.layout.form"
xmlns="sap.m">
<Panel headerText="Table Panel">
<Table id="myTable" items="{/WaybillsPlaces}" mode="SingleSelectMaster" select="onRowPressed" updateFinished="onUpdateFinished">
<columns>
<Column hAlign="Center">
<header>
<Text text="Number" />
</header>
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{CoNumber}" />
</cells>
</ColumnListItem>
</items>
</Table>
</Panel>
<Panel id="Panel1" headerText="onAfterRendering Data Binding">
<Label text="First Item - Property binding:"></Label>
<Input id="Input1"></Input>
<Label text="First Item - Element binding:"></Label>
<Input value="{CoNumber}"></Input>
</Panel>
<Panel id="Panel2" headerText="onUpdateFinished Data Binding">
<Label text="First Item - Property binding:"></Label>
<Input id="Input2"></Input>
<Label text="First Item - Element binding:"></Label>
<Input value="{CoNumber}"></Input>
</Panel>
<Panel id="Panel3" headerText="onRowPressed Data Binding">
<Label text="Selected Item - Property binding:"></Label>
<Input id="Input3"></Input>
<Label text="Selected Item - Element binding:"></Label>
<Input value="{CoNumber}"></Input>
</Panel>
</mvc:View>
</script>
<script>
// define a new (simple) Controller type
sap.ui.controller("my.own.controller", {
onAfterRendering: function(){
var oTable = this.getView().byId('myTable');
var oFirstItem = oTable.getItems()[0]; // This is your ColumnListItem object in the first row
var oFirstCellItem = oFirstItem.getCells()[0]; // This is your Text object in the first cell of the first row
var sFirstItemDataPath = oFirstCellItem.getBindingContext().getPath();
this.getView().byId("Input1").bindProperty("value", sFirstItemDataPath + "/CoNumber");
this.getView().byId("Panel1").bindElement(sFirstItemDataPath);
},
onUpdateFinished: function(oEvent){
var oTable = oEvent.getSource();
var oFirstItem = oTable.getItems()[0]; // This is your ColumnListItem object in the first row
var oFirstCellItem = oFirstItem.getCells()[0]; // This is your Text object in the first cell of the first row
var sFirstItemDataPath = oFirstCellItem.getBindingContext().getPath();
this.getView().byId("Input2").bindProperty("value", sFirstItemDataPath + "/CoNumber");
this.getView().byId("Panel2").bindElement(sFirstItemDataPath);
},
onRowPressed: function(oEvent){
var oFirstItem = oEvent.getParameter("listItem"); // This is the pressed ColumnListItem object
var oFirstCellItem = oFirstItem.getCells()[0]; // This is your Text object in the first cell of the pressed row
var sFirstItemDataPath = oFirstCellItem.getBindingContext().getPath();
this.getView().byId("Input3").bindProperty("value", sFirstItemDataPath + "/CoNumber");
this.getView().byId("Panel3").bindElement(sFirstItemDataPath);
}
});
// instantiate the View
var myView = sap.ui.xmlview({viewContent:jQuery('#view1').html()}); // accessing the HTML inside the script tag above
// create some dummy JSON data
var data = {
WaybillsPlaces: [{
CoNumber: "Item 1",
},{
CoNumber: "Item 2",
},{
CoNumber: "Item 3",
}]
};
// create a Model and assign it to the View
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
myView.setModel(oModel);
// put the View onto the screen
myView.placeAt('content');
</script>
</head>
<body id='content' class='sapUiBody'>
</body>
</html>
EDIT2: Bind a form input to a certain property in a OData Model
Here I'm gonna use Northwind OData service, for ease of use, but you just need to use your own model. I used the "Customers" entitySet (a.k.a "Customers" DB table), and the "CustomerName" property in this entitySet.
In your case (as per the given OData in the description, you should use the 'WaybillsPlaces' entity and your 'CoNumber' property. If you want to access one specific entry, provide the Key between parenthesis in the binding URL (in your case: WaybillsPlaces('4610103052')).
I highly recommend you to read more about OData binding in UI5 (here and here). In a productive application, please set your OData model in the manifest.json file, to be sure that the $metadata call is done when the application starts, avoiding this way performance and many other issues.
HERE THE SNIPPET

sap.ui.table table row selector disable in sapui5

Is it possible to disable row selector for particular rows. setEnable method is not available for sap.ui.table. Please find the attached screenshot for better understanding.
please go through the following code. It might help you.
sap.ui.controller("my.controller", {
onInit: function() {
var model = new sap.ui.model.json.JSONModel([
{Product: "Power Projector 4713", Weight: "33"},
{Product: "Gladiator MX", Weight: "33"},
{Product: "Hurricane GX", Weight: "45"},
{Product: "Webcam", Weight: "33"},
{Product: "Monitor Locking Cable", Weight: "41"},
{Product: "Laptop Case", Weight: "64"}
]);
var vw = this.getView();
vw.setModel(model);
// disable checkboxes
var tbl = vw.byId('tblProduct');
tbl.addDelegate({
onAfterRendering: function() {
var header = this.$().find('thead');
var selectAllCb = header.find('.sapMCb');
selectAllCb.remove();
this.getItems().forEach(function(r) {
var obj = r.getBindingContext().getObject();
var enabled = parseInt(obj.Weight, 10) > 40;
var cb = r.$().find('.sapMCb');
var oCb = sap.ui.getCore().byId(cb.attr('id'));
oCb.setEnabled(enabled);
});
}
}, tbl);
}
});
var oView = sap.ui.xmlview({
viewContent: jQuery('#chartView').html()
}).placeAt('content');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-libs="sap.m"></script>
<script id="chartView" type="sapui5/xmlview">
<mvc:View
controllerName="my.controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<App>
<pages>
<Page title="Table CheckBox Disable" class="marginBoxContent" >
<content>
<Table id="tblProduct" mode= "MultiSelect"
selectionChange = "rowSelect"
items="{/}">
<columns>
<Column>
<Label text="Product" />
</Column>
<Column>
<Label text="Weight" />
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{Product}" />
<Text text="{Weight}" />
</cells>
</ColumnListItem>
</items>
</Table>
</content>
</Page>
</pages>
</App>
</mvc:View>
</script>
</head>
<body class="sapUiBody">
<div id='content'></div>
</body>
</html>
Regards,
Farooq.

binding data to table

How to bind data to using odata model? I'm getting error like Resource not found for the segment 'results'.
My code:
var url = "/sap/opu/odata/sap/ZODATA_SERVICE_NAME";
var oModel = new sap.ui.model.odata.ODataModel(url,false);
oModel.read("/EntityDataSet", null, null, true, function(oData) {
that.getView().setModel(oModel,"student");
},
function(error) {
});
<Table headerDesign="Standard"
items="{student>/results}"
id="table" >
<columns>
<Column >
<header>
<Label text="studentName" width="100%"/>
</header>
</Column>
<Column >
<header>
<Label text="studentRank" width="100%"/>
</header>
</Column>
</columns>
<items>
<ColumnListItem >
<cells>
text="{student>StudentName}"/>
text="{student>Rank}"/>
</cells>
</ColumnListItem>
</items>
</Table>
the ODataMOdel you are using is deprecated, make sure to use the v2.ODataModel instead
you don't need to execute an HTTP call via JavaScript (ODataModel.read(...) ) to get the data in order to bind it to the table.
I think you did not clearly understand OData and models in UI5. Having a look at the official SAPUI5 Tutorials might help you out.
Anyway, here is a running jsbin example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SAPUI5 single file template | nabisoft</title>
<script
src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-bindingSyntax="complex"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"></script>
<!-- use "sync" or change the code below if you have issues -->
<!-- XMLView -->
<script id="myXmlView" type="ui5/xmlview">
<mvc:View
controllerName="MyController"
xmlns="sap.m"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc">
<Table
id="myTable"
growing="true"
growingThreshold="10"
growingScrollToLoad="true"
busyIndicatorDelay="0"
items="{/Customers('ALFKI')/Orders}">
<headerToolbar>
<Toolbar>
<Title text="Orders of ALFKI"/>
<ToolbarSpacer/>
</Toolbar>
</headerToolbar>
<columns>
<Column>
<Text text="OrderID"/>
</Column>
<Column>
<Text text="Order Date"/>
</Column>
<Column>
<Text text="To Name"/>
</Column>
<Column>
<Text text="Ship City"/>
</Column>
</columns>
<items>
<ColumnListItem type="Active">
<cells>
<ObjectIdentifier title="{OrderID}"/>
<Text
text="{
path:'OrderDate',
type:'sap.ui.model.type.Date',
formatOptions: {
style: 'medium',
strictParsing: true
}
}"/>
<Text text="{ShipName}"/>
<Text text="{ShipCity}"/>
</cells>
</ColumnListItem>
</items>
</Table>
</mvc:View>
</script>
<script>
sap.ui.getCore().attachInit(function () {
"use strict";
//### Controller ###
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/odata/v2/ODataModel"
], function (Controller, ODataModel) {
"use strict";
return Controller.extend("MyController", {
onInit : function () {
// in component based apps you would not
// even need this piece of code:
this.getView().setModel(
new ODataModel("https://cors-anywhere.herokuapp.com/services.odata.org/V2/Northwind/Northwind.svc/", {
json : true,
useBatch : false
})
);
}
});
});
//### THE APP: place the XMLView somewhere into DOM ###
sap.ui.xmlview({
viewContent : jQuery("#myXmlView").html()
}).placeAt("content");
});
</script>
</head>
<body class="sapUiBody">
<div id="content"></div>
</body>
</html>
try changing
that.getView().setModel(oModel,"student");
to
this.getView().setModel(oModel,"student");
that.getView().setModel(oModel,"student"); //incorrect
this.getView().setModel(oModel,"student"); //refers to this particular controller

SAPUI5: Refreshing table contents after oData.read

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();