SelectedItem BindingContext not found UI5 application - sapui5

I am trying to find the binding context of the selectedItem. Even after passing modelName to bindingContext, I get undefined. When I do oEvent.getSourcer() and see the oBindingContexts it is blank. Also the oBindingInfos has ocontext undefined. Though it has sPath. The correct sPath. How can I get the array index in this scenario?
oNewField = new sap.m.Select({
enabled: "{order>/" + Type+ "/" + i + "/fieldEnabled}",
forceSelection: false,
width: "90%",
// Add dropdoen Items
items: [
new sap.ui.core.ListItem({
key: " ",
text: " "
}),
new sap.ui.core.ListItem({
key: "{order>/" + Type+ "/" + i + "/DefaultValue}",
text: "{order>/" + Type+ "/" + i + "/DefaultValue}"
})
],
change : function(evt) {
that.onChange(evt);
},
});
var selectedKey = this.getView().getModel('order').getProperty(
"/" + Type+ "/" + i + "/DefaultValue");
oNewField.setSelectedKey(selectedKey);
**On Change Function **
onChange: function(oEvent) {
debugger;
var key = oEvent.getSource().getSelectedItem().getKey();
//need to get BindingContext here.
var oContext =
oEvent.getSource().getSelectedItem().getBindingContext('order')
//gives undefined
},

You are not doing any aggregation binding at all. Therefore there is no context to retrieve. You are hardcoding 2 items in your items aggregation.
Check this snippet. It shows you multinple things you can do. I hope onw of them is what your are looking for.
JSBIN: https://jsbin.com/kumudufaje/edit?html,output
<!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_belize_plus'
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">
<Panel id="myPanel">
</Panel>
</mvc:View>
</script>
<script>
// define a new (simple) Controller type
sap.ui.controller("my.own.controller", {
onInit: function(oEvent){
//aggregation binding
var oSelect = new sap.m.Select({
items: {
path: 'order>/options',
template: new sap.ui.core.Item({
key: {
path: 'order>key'
},
text: {
path: 'order>value'
}
})
},
change: this.onSelection1Change.bind(this)
});
this.getView().byId("myPanel").addContent(oSelect);
for(var i=0; i<3; i++){
//hardcoded items
var oSelect2 = new sap.m.Select({
items: [
new sap.ui.core.ListItem({
key: '',
text: ''
}),
new sap.ui.core.ListItem({
key: {path:'order>/Type/' + i + '/DefaultValue'},
text: {path:'order>/Type/' + i + '/DefaultValue'}
}),
],
change: this.onSelection2Change.bind(this)
});
this.getView().byId("myPanel").addContent(oSelect2);
}
},
onSelection1Change(oEvent){
var oContext = oEvent.getSource().getSelectedItem().getBindingContext('order')
console.log(oContext); //This prints the binded context
var oModel = oContext.getModel();
console.log(oModel); //This prints the whole model
var oSelectedEntry = oModel.getProperty(oContext.getPath());
console.log(oSelectedEntry); //This prints the data
},
onSelection2Change(oEvent){
var sKey = oEvent.getSource().getSelectedItem().getKey();
console.log(sKey); //This prints the selected item key
var sValue = oEvent.getSource().getSelectedItem().getKey();
console.log(sValue); //This prints the selected item value
var oKeyBinding = oEvent.getSource().getSelectedItem().getBinding('key')
console.log(oKeyBinding); //This prints the binding of the key property, if any
if(oKeyBinding){
var oModel = oKeyBinding.getModel();
console.log(oModel); // This prints the model binded key property, if any
}
}
});
/*** THIS IS THE "APPLICATION" CODE ***/
// create some dummy JSON data
var data = {
options: [{
key: '1',
value: 'option 1'
},{
key: '2',
value: 'option 2'
},{
key: '3',
value: 'option 3'
}],
Type:[
{DefaultValue: 'Default Value1'},
{DefaultValue: 'Default Value2'},
{DefaultValue: 'Default Value3'}
]
};
var oJSONModel = new sap.ui.model.json.JSONModel();
oJSONModel.setData(data);
// instantiate the View
var myView = sap.ui.xmlview({viewContent:jQuery('#view1').html()}); // accessing the HTML inside the script tag above
myView.setModel(oJSONModel, "order");
// put the View onto the screen
myView.placeAt('content');
</script>
</head>
<body id='content' class='sapUiBody'>
</body>
</html>

oEvent.getSource().getSelectedItem().getBindingContext()
You've got it completely right. Note that oEvent.getSource() points to the sap.m.Select. You need another getSelectedItem() to go to the selected sap.ui.core.Item.

Related

Bootstrap-vue: Auto-select first hardcoded <option> in <b-form-select>

I'm using b-form-select with server-side generated option tags:
<b-form-select :state="errors.has('type') ? false : null"
v-model="type"
v-validate="'required'"
name="type"
plain>
<option value="note" >Note</option>
<option value="reminder" >Reminder</option>
</b-form-select>
When no data is set for this field I want to auto-select the first option in the list.
Is this possible? I have not found how to access the component's options from within my Vue instance.
your v-model should have the value of the first option.
example
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: 'a',
options: [
{ value: null, text: 'Please select an option' },
{ value: 'a', text: 'This is First option' },
{ value: 'b', text: 'Selected Option' },
{ value: { C: '3PO' }, text: 'This is an option with object value' },
{ value: 'd', text: 'This one is disabled', disabled: true }
]
}
}
}
</script>
You can trigger this.selected=${firstOptionValue} when no data is set.
what if we don't know what the first option is. The list is generated?
if you have dynamic data, something like this will work.
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: [],
options: [],
};
},
mounted: function() {
this.getOptions();
},
methods: {
getOptions() {
//Your logic goes here for data fetch from API
const options = res.data;
this.options = res.data;
this.selected = options[0].fieldName; // Assigns first index of Options to model
return options;
},
},
};
</script>
If your options are stored in a property which is loaded dynamically:
computed property
async computed (using AsyncComputed plugin)
through props, which may change
Then you can #Watch the property to set the first option.
That way the behavior of selecting the first item is separated from data-loading and your code is more understandable.
Example using Typescript and #AsyncComputed
export default class PersonComponent extends Vue {
selectedPersonId: string = undefined;
// ...
// Example method that loads persons data from API
#AsyncComputed()
async persons(): Promise<Person[]> {
return await apiClient.persons.getAll();
}
// Computed property that transforms api data to option list
get personSelectOptions() {
const persons = this.persons as Person[];
return persons.map((person) => ({
text: person.name,
value: person.id
}));
}
// Select the first person in the options list whenever the options change
#Watch('personSelectOptions')
automaticallySelectFirstPerson(persons: {value: string}[]) {
this.selectedPersonId = persons[0].value;
}
}

How to add "select" in dojo tooltipdialog content programmatically?

I want to display dojo select inside a dijit/TooltipDialog. The items of the dojo select are dynamically loaded. So I want to add this select programmaticaly. The content of TooltipDialog can be an object but select needs a domNode to be held. The code is :
<head>
<script>
require([
"dojo/parser",
"dijit/form/Select",
"dijit/TooltipDialog",
"dojo/on",
"dojo/dom",
"dojo/_base/lang",
"dijit/popup",
"dojo/data/ObjectStore",
"dojo/store/Memory",
"dojo/domReady!"
], function(parser,Select,TooltipDialog,on,dom,lang,popup, ObjectStore, Memory){
parser.parse();
var t={mySel:null};
var store = new Memory({
data: [
{ id: "foo", label: "Foo" },
{ id: "bar", label: "Bar" }
]
});
var os = new ObjectStore({ objectStore: store });
t.mySel = new Select({
store: os
}, "ttt");
var myTooltipDialog = new TooltipDialog({
content: t,
onMouseLeave: function(){
popup.close(myTooltipDialog);
}
});
on(dom.byId("mmm"),"mouseover" ,lang.hitch(this,function(e){
popup.open({
popup: myTooltipDialog,
orient: ["above-centered","above","below"],
around:dom.byId('mmm')
});
t.mySel.startup();
}));
t.mySel.on("change", function(){
console.log("my value: ", this.get("value"))
})
})
</script>
</head>
<body class="claro">
<div id="ttt" > tttt</div><br>
<div id="mmm" > tttt</div><br>
</body>
You are assignign an object t the tooltip content not a domenode
so try to make these change :
var myTooltipDialog = new TooltipDialog({
content: t.mySel.domNode,
onMouseLeave: function() {
popup.close(myTooltipDialog);
}
}

Not able to bind column data when there is space in json

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>OData Date Table Multiple Sorters</title>
<link rel="stylesheet" type="text/css" href="">
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" type="text/javascript" data-sap-ui-libs="sap.ui.core,sap.ui.commons,sap.ui.table" data-sap-ui-theme="sap_goldreflection">
</script>
<script>
var airsideTableDataOriginal=
//{"genericTableModel":
[
{"columnId":"col1","WS":"WS 1","Status":0},
{"columnId":"col 2","WS":"WS 2","Status":1},
{"columnId":"col3","WS":"WS 3","Status":2},
{"columnId":"col4","WS":"WS 4","Status":3},
{"columnId":"col5","WS":"WS 5","Status":4},
];
var aColumnData = [{
columnId: "col1"
}, {
columnId: "col 2"
}, {
columnId: "col3"
}, {
columnId: "col4"
}, {
columnId: "col5"
}];
var aData = [{
"col 2": "WS 2",
col3: "WS 3",
col4: "WS 4",
col5: "WS 5"
}];
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
columns: aColumnData,
rows: aData
});
var oTable = new sap.ui.table.Table({
title: "Table column and data binding",
showNoData : true,
columnHeaderHeight : 10,
visibleRowCount: 7
});
oTable.setModel(oModel);
oTable.bindColumns("/columns", function(index, context) {
var sColumnId = context.getObject().columnId;
var tempJson=airsideTableDataOriginal;
return new sap.ui.table.Column({
id : sColumnId,
label: sColumnId,
template: new sap.ui.commons.Button({
text : {
path: sColumnId,
formatter: function(value){
if(value!=null){
var specificJson= $.grep(tempJson, function( n, i ) {
return n.columnId === sColumnId.toString() && n.WS === value.toString();
});
if(specificJson[0].Status == 1){
this.setIcon("sap-icon://accept");
this.setStyle(sap.ui.commons.ButtonStyle.Accept);
}
}
if(value === "" || value == undefined){
this.setVisible(false);
}
return value ;
}
},
}),
sortProperty: sColumnId,
filterProperty: sColumnId
});
});
oTable.bindRows("/rows");
oTable.placeAt("content");
</script>
</head>
<body class="sapUiBody" id="body" role="application">
<div id="content"></div>
</body>
</html>
As per the above code there is space between col 2 which gives error "col 2" is not a valid ID.. Here is the bin. But when I replace col 2 with col2 it works fine. But in real time I get spaces in data so how to fix it so that it would work with spaces also.
I would guess, that the error comes from the invalid ID of the Column object: id : sColumnId, (the first line after return new sap.ui.table.Column({) and not from the binding.
Like Mark said in his comment Element IDs cannot contain spaces. But the ID is not visible to the User and you can just replace the spaces of the Column.id while assigning or you can skip the id assignment at all to get automaticaly generated ids.
A client who demands spaces in their ID's I would 1) definitely steer clear from, and if that's not possible, 2) educate them that their "requirement" is utter [...]
Nevertheless, I would simply replace the spaces with underscores (it's really simple Javascript):
airsideTableDataOriginal.forEach(function(obj) {
obj.columnId = obj.columnId.replace(/ /g,"_");
});
aColumnData.forEach(function(obj) {
obj.columnId = obj.columnId.replace(/ /g,"_");
});
aData.forEach(function(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (~property.indexOf(" ")) {
var newProperty = property.replace(/ /g,"_");
obj[newProperty] = obj[property];
delete obj[property];
}
}
}
});

Adding columns and button to column in Openui5 table dynamically

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>OData Date Table Multiple Sorters</title>
<link rel="stylesheet" type="text/css" href="">
<script id="sap-ui-bootstrap" src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" type="text/javascript" data-sap-ui-libs="sap.ui.core,sap.ui.commons,sap.ui.table" data-sap-ui-theme="sap_goldreflection">
</script>
<script>
var aColumnData = [{
columnId: "col1"
}, {
columnId: "col2"
}, {
columnId: "col3"
}, {
columnId: "col4"
}, {
columnId: "col5"
}];
var aData = [{
col1: "Row 1 col 1",
col2: "Row 1 col 2",
col3: "Row 1 col 3",
col4: "Row 1 col 4",
col5: "Row 1 col 5"
}, {
col1: "Row 2 col 1",
col2: "Row 2 col 2",
col3: "Row 2 col 3",
col4: "Row 2 col 4",
col5: "Row 2 col 5"
}];
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
columns: aColumnData,
rows: aData
});
var oTable = new sap.ui.table.Table({
title: "Table column and data binding",
showNoData : true,
columnHeaderHeight : 10,
visibleRowCount: 7
});
oTable.setModel(oModel);
oTable.bindColumns("/columns", function(index, context) {
var sColumnId = context.getObject().columnId;
//alert(sColumnId.);
return new sap.ui.table.Column({
id : sColumnId,
label: sColumnId,
// template: sColumnId,
template: new sap.ui.commons.Button({
text : sColumnId,
icon :
"sap-icon://accept",
enabled: true,
press: function(e) {
}}),
sortProperty: sColumnId,
filterProperty: sColumnId
});
});
oTable.bindRows("/rows");
oTable.placeAt("content");
</script>
</head>
<body class="sapUiBody" id="body" role="application">
<div id="content"></div>
</body>
</html>
Instead of column values as Button text I get the column names. But if I change the template value from button to sColumnId as stated below I get the output correct :
template: sColumnId,
Here is the link for jsbin: http://jsbin.com/horozew/edit?html,output
You assign a literal string to the text property of your button.
Instead you have to bind the text property of the button to the model with your sColumnId as binding path:
text: { path: sColumnId }
See jsbin.
If assign a string to the template aggregation of the column, the column creates a TextView and binds its text property with the given string as path in its setter.
Edit: Some more information as requested in comment.
You have bound the columns of your table to the datasource (the data from aColumnData at the model path /columns). In the function that you give bindColumns() as second parameter you create the Column objects for your table. The function is called for each item in aColumnData. With that you create the template - a Button - and bind its value to the model specifying a relative path (relative to /rows).
Then you bind your rows of the table to the datasource (the data from aData at the model path /rows). For each item in aData a row will be created. Each row gets a binding Context that points to the corresponding aData entry and enables relative paths inside the row.
The template of each column you created before will be cloned for each row. At this point you could access the data of a single cell.
A quite simple way to do that is a formatter function:
text: {
path: sColumnId,
formatter: function(value){
return "Hi " + value ;
}
}
Edit: Accessing both the value and the column id
Thanks to javascript closures you can do something like this to access both - the sColumnId and the cell value (jsbin):
template: new sap.ui.commons.Button({
text : {path: sColumnId },
icon : {path: sColumnId, formatter: function(value) { if (sColumnId === "col2" && value > "Row 2") return "sap-icon://accept"; else return "" } },
enabled: true,
press: function(e) {
}}),

Custom Transition for sap.m.App

I want to write a custom transition for sap.m.Page transitions.
How Do I start off with this?
Exactly I want to know regarding any documentation, How to create a custom transition and register the same so that it can be used in an SAP UI5 Application.
Thanks in Advance
A Sample implementation of custom transition when App navigates. Click on the list item to find the transition. There is no documentaion on it. This is just a hack.
jQuery.sap.require('sap.m.NavContainer');
jQuery.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-core');
jQuery.sap.require('sap.ui.thirdparty.jqueryui.jquery-ui-effect')
jQuery.sap.require('sap.ui.thirdparty.jqueryui.jquery-effects-core');
jQuery.sap.require('sap.ui.thirdparty.jqueryui.jquery-effects-clip');
sap.m.NavContainer.transitions["custom"] = {
to: function(oFromPage, oToPage, fCallback) {
window.setTimeout(function(){
oFromPage.$().toggle("clip");
oToPage.$().toggle("clip");
fCallback();
},600);
},
back: function(oFromPage, oToPage, fCallback) {
window.setTimeout(function(){
debugger;
oFromPage.$().toggle("clip");
oToPage.$().toggle("clip");
fCallback();
},600);
}
};/* code for transition */
var data = {
names: [
{firstName: "Peter", lastName: "Mueller"},
{firstName: "Petra", lastName: "Maier"},
{firstName: "Thomas", lastName: "Smith"},
{firstName: "John", lastName: "Williams"},
{firstName: "Maria", lastName: "Jones"}
]
};
// create a Model with this data
var model = new sap.ui.model.json.JSONModel();
model.setData(data);
var list = new sap.m.List({
headerText:"Names"
});
list.bindItems({
path : "/names",
sorter : new sap.ui.model.Sorter("lastName"),
template : new sap.m.StandardListItem({
title: "{lastName}",
description: "{firstName}",
type: sap.m.ListType.Navigation,
press:function(evt){
var oBindingContext = evt.getSource().getBindingContext();
page2.setBindingContext(oBindingContext);
app.to("page2","custom");
}
})
});
// create the page holding the List
var page1 = new sap.m.Page("page1",{
title: "List Page",
content : list
});
// create the detail page
var page2 = new sap.m.Page("page2", {
title: "Detail Page",
showNavButton: true,
navButtonPress: function(){
app.back();
},
content : [
new sap.ui.layout.form.SimpleForm({
title: "Details for {firstName} {lastName}",
content: [
new sap.m.Label({text: "First Name"}),
new sap.m.Text({text: "{firstName}"}),
new sap.m.Label({text: "Last Name"}),
new sap.m.Text({text: "{lastName}"})
]
})
]
});
// create a mobile App holding the pages and place the App into the HTML document
var app = new sap.m.App({
pages: [page1, page2]
}).placeAt("content");
// set the model to the App; it will be propagated to the children
app.setModel(model);
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<title>Custom jQuery transition</title>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m,sap.ui.layout"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-theme="sap_bluecrystal"></script>
</head>
<body id="content" class="sapUiBody">
</body>
</html>