Access model defined in manifest - sapui5

Using single model definition in manifest.json
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "....i18n.i18n"
}
},
"": {
"dataSource": "mainService"
}
}
i can bind to model from XML and it's work
<List items="{path: '/myOneSet'}"> ... </List>
<List items="{path: '/myTwoSet'}"> ... </List>
but i can not access to it from code
this.getView().getModel().getProperty('/myOneSet')
or
this.getView().getModel().getProperty('/myOneSet/>param')
not work. How it accessible?

If mainService is an OData service, then your model is an ODataModel. You can access data via methods described in the API, e.g.: read()
this.getView().getModel().read('/myOneSet', {
success: function(oData, response) {
// do sg. with oData
}
});
Most of its data access methods has a second parameter-object with a success function callback. This function will be called asynchronously with the data on the given path upon successful data retrieval from the datasource. Most of the ODataModel API methods works with callbacks. You can read more about callbacks here.

If you defined model in the manifest.json file then you can access it via Component. If you created your project via template then you have a BaseController.js file which is the ancestor of your other controllers and there is a function getComponentModel. So, I would suggest you to try this code in your controller:
this.getComponentModel().getProperty('/myOneSet')

Because of the property name that you try to access I assume you are using an ODataModel. Is that correct?
If that's true you have to consider a few things... ODataModel.getProperty() does not trigger requests. Instead it will return whats already available. If you want to trigger a request you should execute an ODataModel.read(). If you want to get the loaded data from the ODataModel then you should also know when the data has been loaded. This you can achieve by attaching a change event handler when you do the binding.
Instead of describing how to access the data of an ODataModel I wrote s little jsbin example for you (or see below). Just check the change event handler. There are multiple ways to access the data.
<!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">
<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>
<!-- filled via bindItems() in controller -->
</items>
</Table>
</mvc:View>
</script>
<!-- XML Fragment -->
<script id="myXMLFragment" type="ui5/fragment">
<core:FragmentDefinition
xmlns="sap.m"
xmlns:core="sap.ui.core">
<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>
</core:FragmentDefinition>
</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 () {
this.getView().setModel(
new ODataModel("https://cors-anywhere.herokuapp.com/services.odata.org/V2/Northwind/Northwind.svc/", {
json : true,
useBatch : false
})
);
var sPath = "/Customers('ALFKI')/Orders";
var oTable = this.byId("myTable");
var oTemplate = sap.ui.xmlfragment({
fragmentContent : jQuery("#myXMLFragment").html()
});
oTable.bindItems({
path : sPath,
template : oTemplate,
templateShareable : false,
sorter : null,
filters : null,
events : {
change : function (oEvent) {
var oModel, oListBnd, aContexts, i, oObj;
console.log("1. Example: ODataModel.getProperty() does not trigger a request (but here we have the data already)!");
oModel = this.getView().getModel();
console.dir( oModel.getProperty("/Orders(10643)")); //OK
console.dir( oModel.getProperty("/Orders") ); //Not OK
console.dir( oModel.getData("/") ); //DANGER: Could contain different entities!!!!!
console.log("2. Example: Accessing the Data via ListBinding");
oListBnd = oTable.getBinding("items"); // get the ListBinding
//oListBnd = oEvent.getSource(); // this works here inside the change handler
aContexts = oListBnd.getCurrentContexts(); // the the contexts
for(i=0; i<aContexts.length; i++){
oObj = aContexts[i].getObject(); // access the items/objects
console.dir( oObj );
}
}.bind(this)
}
});
}
});
});
//### 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>

Hi Just declare this is manifest
"models": {
"createMod": {
"preload": true,
"dataSource": "CreateService",
"settings": {
}
}
and Try to Access by Controller using.
var oModelCheck = that.getOwnerComponent().getModel("createMod");

Related

How to know row number when typing in input field in table

In my XML view, I have a Table, in that Table I have Input field at a particular column, and I have a function for liveChange event of that Input field. Code is like below:
<Table ...>
<columns> ... </columns>
<items>
<ColumnListItem>
<cells>
......
<Input type ="Number" value="{...}" liveChange="qtyChanged"/>
</cells>
</ColumnListItem>
</items>
</Table>
In qtyChanged(), I need to know the row number on which user is editing. How to achieve it?
You can achieve it using indexOfItem() of sap.m.Table
qtyChanged: function(oEvent){
var oRow = oEvent.getSource().getParent();//Get Row
var oTable = oRow.getParent();// Get Table
var iRowIndex = oTable.indexOfItem(oRow);//Get Row index
}
Note: If the response data is more then table row limit then scroll will appear, then the row index will not work properly.
you can get the binding context and then the path. you're also able to get the object itself like this (working example http://jsbin.com/hutuvo/edit?html,output)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<title>MVC</title>
<script id="sap-ui-bootstrap" type="text/javascript"
src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m,sap.ui.table"
data-sap-ui-xx-bindingSyntax="complex">
</script>
<script id="oView" type="sapui5/xmlview">
<mvc:View
controllerName="sap.example.Controller"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
height="100%">
<Table id="idProductsTable" items="{ path: 'suppliers>/suppliers'}">
<columns>
<Column><Text text="Supplier" /></Column>
<Column><Text text="Quantity" /></Column>
</columns>
<items>
<ColumnListItem>
<cells><Text text="{suppliers>SupplierName}" /></cells>
<cells><Input type ="Number" value="{suppliers>Quantity}" liveChange="qtyChanged" /></cells>
</ColumnListItem>
</items>
</Table>
</mvc:View>
</script>
<script>
sap.ui.define([ "sap/ui/core/mvc/Controller", "sap/ui/model/json/JSONModel"],
function(Controller, JSONModel) {
"use strict";
var oPageController = Controller.extend("sap.example.Controller", {
onInit: function() {
var oView = this.getView();
oView.setModel(new JSONModel({
suppliers: [
{
SupplierName: "Apple",
Product: "iPhone",
Quantity: 0
}, {
SupplierName: "Samsung",
Product: "Galaxy",
Quantity: 0
}
]
}), "suppliers");
},
qtyChanged: function(oEvent) {
var oContext = oEvent.getSource().getBindingContext("suppliers");
var oPath = oContext.getPath();
var index = parseInt(oPath.substring(oPath.lastIndexOf("/") + 1), 10);
console.log(index);
console.log(oContext.getObject());
}
});
return oPageController;
});
var oView = sap.ui.xmlview({
viewContent: jQuery('#oView').html()
});
oView.placeAt('content');
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>

How to Make List Items Reorderable?

I have to create a table (sap.m.Table) in SAPUI5 where rows can be deleted, reordered, and clicked on to open a dialog. So far I've figured out that I can set the Table to mode="delete" and ColumnListItem to type="Navigation" to achieve deleting rows and clicking on rows to open dialogs at the same time:
Is it possible to add the functions to reorder rows to this?
You can use a "editModeEnabled" variable in your view model to change the Table mode to "SingleSelectLeft" and show/hide some buttons. Then in "editMode", use some buttons to insert and remove the items of the table wherever you want
Here a snippet
<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 xmlns="sap.m" xmlns:mvc="sap.ui.core.mvc" controllerName="my.own.controller">
<Page>
<Table id="myTable" mode="{= ${viewModel>/editModeEnabled} ? 'SingleSelectLeft' : 'SingleSelectMaster'}" items="{path:'json>/rows'}">
<headerToolbar>
<Toolbar>
<ToolbarSpacer></ToolbarSpacer>
<Button text="Edit" press="onEditPressed" visible="{= ${viewModel>/editModeEnabled} ? false : true}"></Button>
<Button icon="sap-icon://slim-arrow-down" press="onDownPressed" visible="{= ${viewModel>/editModeEnabled} ? true : false}"></Button>
<Button icon="sap-icon://slim-arrow-up" press="onUpPressed" visible="{= ${viewModel>/editModeEnabled} ? true : false}"></Button>
<Button text="Finish" press="onFinishEditPressed" visible="{= ${viewModel>/editModeEnabled} ? true : false}"></Button>
</Toolbar>
</headerToolbar>
<columns>
<Column>
<Text text="Column1" />
</Column>
<Column>
<Text text="Column2" />
</Column>
</columns>
<items>
<ColumnListItem>
<Text text="{json>col1}"></Text>
<Text text="{json>col2}"></Text>
</ColumnListItem>
</items>
</Table>
</Page>
</mvc:View>
</script>
<script>
// define a new (simple) Controller type
sap.ui.controller("my.own.controller", {
onInit: function(){
var oViewModelData = {
editModeEnabled: false
};
var oViewModel = new sap.ui.model.json.JSONModel();
this.getView().setModel(oViewModel, "viewModel")
},
onEditPressed: function() {
this.getView().getModel("viewModel").setProperty("/editModeEnabled", true);
},
onFinishEditPressed: function(){
this.getView().getModel("viewModel").setProperty("/editModeEnabled", false);
},
onUpPressed: function(oEvent){
var oSelectedItem = this.getView().byId("myTable").getSelectedItem();
var oCurrentIndex = this.getView().byId("myTable").indexOfItem(oSelectedItem);
if(oCurrentIndex > 0){
this.getView().byId("myTable").removeItem(oSelectedItem);
this.getView().byId("myTable").insertItem(oSelectedItem, oCurrentIndex-1);
}
},
onDownPressed: function(oEvent){
var oSelectedItem = this.getView().byId("myTable").getSelectedItem();
var oCurrentIndex = this.getView().byId("myTable").indexOfItem(oSelectedItem);
if(oCurrentIndex < this.getView().byId("myTable").getItems().length){
this.getView().byId("myTable").removeItem(oSelectedItem);
this.getView().byId("myTable").insertItem(oSelectedItem, oCurrentIndex+1);
}
}
});
/*** THIS IS THE "APPLICATION" CODE ***/
// create a Model and assign it to the View
//Using a small JSON model
var myData = {
rows: [
{
col1: "Row1Col1",
col2: "Row1Col2",
},{
col1: "Row2Col1",
col2: "Row2Col2",
},{
col1: "Row3Col1",
col2: "Row3Col2",
}
]
};
var oJSONModel = new sap.ui.model.json.JSONModel(myData);
// instantiate the View
var myView = sap.ui.xmlview({
viewContent: jQuery('#view1').html()
}); // accessing the HTML inside the script tag above
// Set the Models
myView.setModel(oJSONModel, 'json');
myView.placeAt('content');
</script>
</head>
<body id='content' class='sapUiBody'>
</body>
</html>

Deselect Radiobuttons when leaving the view via cancel button

I have a table(sap.m.table) with radiobutton control in the first column.
The table shows different "prices" from which the user should be able to choose only one. My problem is, when i use the cancel button it should delete all selections made (in dropdowns, datefilter, etc.). It works for every control except radiobutton.
<ColumnListItem> <cells>
<RadioButton id="radiobutton" groupName="tablebuttons" select="onSelect"/>.....
When i leave the view with the cancel button and then open it again in the same session, the previous selected radiobutton is still selected.
I cant find any method to set it to unselected. When i use this.getView().byId("radiobutton").getSelected()
it always gives back "false".
Is it because there is one button for each table row and i only select (the first?) one? If so, how can i search all button for the selected one and deselect it?
You must have added id="radiobutton" to the template list item which is used for aggregation binding. That is why calling byId("radiobutton") does not return any rendered radio button but the template instance. If you check the IDs of the radio buttons from the HTML document, you'll notice that they all contain the generated prefix __clone0, __clone1, etc.
I can't find any method to set it to unselected.
To deselect a radio button, use:
In case of RadioButton: .setSelected(false)
In case of RadioButtonGroup: .setSelectedIndex(-1)
But you might not even need any sap.m.RadioButton to add manually to the table. Since sap.m.Table extends from sap.m.ListBase, it can have a radio button in each list item via mode="SingleSelectLeft". Here is a demo:
sap.ui.getCore().attachInit(() => sap.ui.require([
"sap/ui/model/json/JSONModel"
], JSONModel => sap.ui.xmlview({
async: true,
viewContent: `<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
controllerName="MyController"
>
<Table
mode="SingleSelectLeft"
selectionChange=".onSelectionChange"
includeItemInSelection="true"
items="{prices>/}">
<columns>
<Column>
<Text text="Price"/>
</Column>
<Column>
<Text text="Foo"/>
</Column>
</columns>
<items>
<ColumnListItem selected="{prices>selected}" >
<ObjectNumber number="{prices>price}" />
<Text text="bar" />
</ColumnListItem>
</items>
</Table>
<Button
class="sapUiTinyMargin"
text="Deselect"
type="Emphasized"
press=".onResetPress"
/>
</mvc:View>`,
controller: sap.ui.controller("MyController", {
onInit: function() {
const model = new JSONModel(this.createModelData());
this.getView().setModel(model, "prices");
},
onResetPress: function() {
const model = this.getView().getModel("prices");
model.setProperty("/", this.createModelData());
},
createModelData: () => [{
price: 111.01,
}, {
price: 222.0245,
}, {
price: 333,
}],
}),
}).loaded().then(view => view.placeAt("content"))));
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m"
data-sap-ui-preload="async"
data-sap-ui-theme="sap_belize"
data-sap-ui-compatVersion="edge"
data-sap-ui-xx-waitForTheme="true"
></script><body id="content" class="sapUiBody sapUiSizeCompact"></body>
IMO, you should use a model to set/reset values and not called the setter function of control. here is an example of using MVC
http://jsbin.com/zijajas/edit?html,js,output
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<title>MVC</title>
<script id="sap-ui-bootstrap" type="text/javascript"
src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m,sap.ui.table"
data-sap-ui-xx-bindingSyntax="complex">
</script>
<script id="oView" type="sapui5/xmlview">
<mvc:View height="100%" controllerName="myView.Template"
xmlns="sap.m"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc"
xmlns:table="sap.ui.table">
<table:Table id="Table1" rows="{/}"
selectionMode="None">
<table:title>
<Button icon="sap-icon://reset" press="reset" />
</table:title>
<table:columns>
<table:Column>
<Label text="Employee name"/>
<table:template>
<Text text="{name}" ></Text>
</table:template>
</table:Column>
<table:Column>
<Label text="Company"/>
<table:template>
<Text text="{company}"></Text>
</table:template>
</table:Column>
<table:Column>
<Label text="Radio"/>
<table:template>
<RadioButtonGroup selectedIndex="{radio}">
<RadioButton text="no" />
<RadioButton text="yes" />
</RadioButtonGroup>
</table:template>
</table:Column>
<table:Column>
<Label text="Bonus"/>
<table:template>
<Input value="{bonus}" />
</table:template>
</table:Column>
</table:columns>
</table:Table>
</mvc:View>
</script>
</head>
<body class="sapUiBody sapUiSizeCompact" role="application">
<div id="content"></div>
</body>
</html>
controller
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
], function(jQuery, Controller, JSONModel) {
"use strict";
var oController = Controller.extend("myView.Template", {
onInit: function(oEvent) {
this.getView().setModel(new JSONModel([{
name : "John",
company: "apple inc",
radio: 0,
bonus: "0"
}, {
name : "Mary",
company: "abc inc",
radio: 0,
bonus: "0"
},
]));
},
reset: function() {
var oModel = this.getView().getModel();
oModel.getProperty('/').forEach(function(item) {
item.radio = 0;
item.bonus = 0;
});
oModel.refresh();
}
});
return oController;
});
var oView = sap.ui.xmlview({
viewContent: jQuery('#oView').html()
});
oView.placeAt('content');

Correct usage for filters when binding items via XMLView

Using sap.m.Select, I have a similar code as this below:
<m:Select
selectedKey='{state}'
items="{
path: 'states>/content',
sorter: {
path: 'name'
}
}">
<core:Item key="{states>id}" text="{states>name}" />
</m:Select>
As want to be able to filter states by country when it is selected in another input, so, I'm trying using filters, which is defined in documentation in:
https://sapui5.netweaver.ondemand.com/docs/api/symbols/sap.ui.base.ManagedObject.html#bindAggregation
https://sapui5.netweaver.ondemand.com/#docs/api/symbols/sap.ui.model.Filter.html
The problem is that I couldn't find anywhere (docs, google, SO, source code, examples, tests) showing how to correctly use it. I tried these 2 ways with no success:
<m:Select
selectedKey='{state}'
items="{
path: 'states>/content',
sorter: {
path: 'name'
},
filters: [{
path: 'countryId',
operator: 'EQ',
value1: '10' // just example
]}
}">
<core:Item key="{states>id}" text="{states>name}" />
</m:Select>
and
# View
<m:Select
selectedKey='{state}'
items="{
path: 'states>/content',
sorter: {
path: 'name'
},
filters: ['.filterByCountry'}
}">
<core:Item key="{states>id}" text="{states>name}" />
</m:Select>
# Controller
...
filterByCountry: new sap.ui.model.Filter({
path: 'countryId',
operator: 'EQ',
value1: '10'
}),
...
Anybody knows the proper way to use it?
Here is how filters work in XML Views - see the 2 examples below I coded for you (use the jsbin links if they don't run here on stackoverflow). They both use the Northwind OData service. As you will see it's pretty much straight forward:
<Select
items="{
path : '/Orders',
sorter: {
path: 'OrderDate',
descending: true
},
filters : [
{ path : 'ShipCountry', operator : 'EQ', value1 : 'Brazil'}
]
}">
Of course, you can add multiple filters as well (see the second example below).
However, keep in mind that the filters are declared in the XMLView. Unfortunately, UI5 is currently not so dynamic to allow changing such filters defined in an XMLView dynamically by only using the binding syntax in the XMLView. Instead you would need some piece of JavaScript code. In your case you could listen for the change event of the other field. In the event handler you would then simply create a new Filter and apply it:
var oSelect, oBinding, aFilters, sShipCountry;
sFilterValue = ...; // I assume you can get the filter value from somewhere...
oSelect = this.getView().byId(...); //get the reference to your Select control
oBinding = oSelect.getBinding("items");
aFilters = [];
if (sFilterValue){
aFilters.push( new Filter("ShipCountry", FilterOperator.Contains, sFilterValue) );
}
oBinding.filter(aFilters, FilterType.Application); //apply the filter
That should be all you need to do. The examples below do not use any JavaScript code for the filter, but I guess you get the idea.
1. Example - Select box:
Run the code: https://jsbin.com/wamugexeda/edit?html,output
<!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">
<Select
items="{
path : '/Orders',
sorter: {
path: 'OrderDate',
descending: true
},
filters : [
{ path : 'ShipCountry', operator : 'EQ', value1 : 'Brazil'}
]
}">
<core:Item key="{OrderID}" text="{OrderID} - {ShipName}" />
</Select>
</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 () {
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>
2. Example - Table:
Run the code: https://jsbin.com/yugefovuyi/edit?html,output
<!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="{
path : '/Orders',
sorter: {
path: 'OrderDate',
descending: true
},
filters : [
{ path : 'ShipCity', operator : 'Contains', value1 : 'rio'},
{ path : 'ShipName', operator : 'EQ', value1 : 'Hanari Carnes'}
]
}">
<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 () {
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>

Get selected item from sap.m.Select from a sapui5 table column

I am using sap.m.Table, where I have 3 columns, as sap.m.text, sap.m.setect and the last one is button.
My model code
var oModel = new sap.ui.model.odata.OData("url");
sap.ui.getCore().setModel(oModel ,"data");
Table view code(cells)
var oTemplate = new sap.m.ColumnListItem({
cells : [
new sap.m.Text({
text: "{data>Address}"
}),
new sap.m.Select({
id:"sel",
items: {
path: "data>/OPERATORS", // this is a diffent table
template: new sap.ui.core.Item({
text: "{data>firstName} {data>lastName}"
})
},
forceSelection: false
}),
new sap.m.Button({
text : "Start",
press : [oController.onPressStart, oController]
})
]
});
oTable.bindItems("data>/ORDR", oTemplate); //differnt table
Working fine, getting all required data on the specific table.(Notice first column is coming from ORDR table and second one is coming from OPERATORS table).
Now on button click I wanted the specific row data. My code as follows -
onPressStart : function(oEvent){
var obj = oEvent.getSource().getBindingContext("data").getObject();
},
"obj" gives me ORDR table row objects(where I pressed the button).
Now I also want the value I will select on the dropdown box. How to get it.
Please suggest, Thank you
JSbin Link - http://jsbin.com/quhomoloqo/edit?html,console,output
See this working example:
Please note how (for the sake of this question) created two models:
One named 'orig' which holds your original OPERATOR and ODRD data, and
one named 'data' which holds a copy of the OPERATOR data, with an added Address property.
See the view code on how the two models are used (the new one for the table, the old one for populating the dropdown)
sap.ui.controller("view1.initial", {
onInit : function(oEvent) {
},
onAfterRendering : function() {
// your original model
var oModel = new sap.ui.model.json.JSONModel();
var oData = {
"ODRD":[
{"Address":"UK"},
{"Address":"US"}
],
"OPERATORS":[
{"firstName":"a","lastName":"b"},
{"firstName":"c","lastName":"d"}
]
};
oModel.setData(oData);
this.getView().setModel(oModel, "orig");
// the model you actually need
var oNewModel = new sap.ui.model.json.JSONModel();
var oNewData = oData.OPERATORS.map(function(result) {
return {
firstName : result.firstName,
lastName : result.lastName,
keyToAddress : null
}
})
oNewModel.setData({
"OPERATORS" : oNewData
});
this.getView().setModel(oNewModel, "data");
},
showData : function(oEvent) {
alert(JSON.stringify(oEvent.getSource().getBindingContext("data").getObject()));
}
});
sap.ui.xmlview("main", {
viewContent: jQuery("#view1").html()
})
.placeAt("uiArea");
<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 id="tbl" items="{data>/OPERATORS}">
<columns>
<Column>
<Text text="First" />
</Column>
<Column>
<Text text="Last" />
</Column>
<Column>
<Text text="ODRD" />
</Column>
<Column>
<Text text="" />
</Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Input value="{data>firstName}" />
<Input value="{data>lastName}" />
<Select items="{orig>/ODRD}" selectedKey="{data>keyToAddress}">
<items>
<core:ListItem key="{orig>Address}" text="{orig>Address}" />
</items>
</Select>
<Button text="Show data" press="showData" />
</cells>
</ColumnListItem>
</items>
</Table>
</mvc:View>
</script>