Dynamic link in MessagePopover fragment not showing - sapui5

I've been developing a UI5 app that uses a model to store notifications. I want to display these notifications inside a MessagePopover that can be triggered using the footer.
The data binding works perfectly. I can see that all the properties are set and match the data inside the model. But the link in the details page is not showing up.
When I use a static Link (i.e. a static link to google.com) that is not using data binding, the link is rendered.
Does anyone of you came across the same problem and has a solution for it?
Here is my code:
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(BaseController) {
return BaseController.extend("test.Test", {
onShowNotificationPopover: function(oEvent){
if (!this._notificationPopover) {
var oMessageTemplate = new sap.m.MessageItem({
type : '{data>type}',
title : '{data>title}',
subtitle : "{data>subtitle}",
description : '{data>description}',
markupDescription : "{data>markupDescription}",
groupName : "{data>groupName}"
});
var oLink = new sap.m.Link({
text : "{data>link/text}",
href : "{data>link/url}",
target : "_blank"
});
/* Working with static */
// oLink = new sap.m.Link({text: "Google", href: "http://google.com", target: "_blank"})
oMessageTemplate.setLink(oLink);
var oPopover = new sap.m.MessagePopover();
oPopover.bindAggregation("items",{
template: oMessageTemplate,
path: "data>/notifications"
});
this._notificationPopover = oPopover;
this.getView().addDependent(this._notificationPopover);
}
this._notificationPopover.toggle(oEvent.getSource());
}
});
});
The view contains the following:
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:f="sap.f" xmlns="sap.m" controllerName="test.Test">
<f:DynamicPage showFooter="true">
<f:footer>
<OverflowToolbar>
<Button icon="sap-icon://message-popup" type="Emphasized"
press="onShowNotificationPopover" />
</OverflowToolbar>
</f:footer>
</f:DynamicPage>
</mvc:View>
And the index.html
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m, sap.f"
data-sap-ui-theme="sap_belize"
data-sap-ui-bindingSyntax="complex"
data-sap-ui-resourceroots='{
"test": "."
}'
>
</script>
<script>
sap.ui.getCore().attachInit(function() {
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
notifications: [{
type: "Error",
title: "Title1",
subtitle: "Subtitle",
description: "This is a description and below you should see a link",
markupDescription: false,
groupName: "notification",
link: {
text: "Click here",
url: "http://www.google.com"
}
}]
});
var oView = sap.ui.xmlview("test.Test");
oView.setModel(oModel, "data");
oView.placeAt("content");
});
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
Example: Popover with dynamic link
Example: Popover with static link

I found a solution for my problem: the event itemPress of MessagePopover.
The event handler inside the controller:
onNotificationItemSelect: function(oEvent){
var oItem = oEvent.getParameter("item"), oBindingContext = oItem.getBindingContext("data");
var oData = oBindingContext.getModel().getProperty(oBindingContext.getPath());
oItem.getLink().setText(oData.link.text);
oItem.getLink().setHref(oData.link.url);
}
And you have to register it:
var oPopover = new sap.m.MessagePopover({
itemSelect: this.onNotificationItemSelect
});
Additional Information
When you display the content of the popover using
console.log(oPopover.getItems()[0].getLink())
the correct properties are shown. see here
But when you search the DOM you can see that the link is copied and does not contain the required binding. see here

Related

How to disable sap.m.Select when only one selection item left

I made an example for this question with the following logic:
A dropdown (sap.m.Select) has 2 options:
But whenever a checkbox above it is checked it only has one option left:
In that case I don't need any of this anymore:
So I found out, that the property editable="false" does exactly what I want in this case:
...but I don't know how to set editable dynamically depending on the current number of options.
Here's the full example:
https://jsfiddle.net/mb0h8v1s/1/
Since you are using a JSONModel you can say something like
editable="{= ${options>/arr1}.length > 1 }"
This is called Expression Binding and lets you use basic JavaScript within your binding.`
This assumes that you always use the same list and change the content of your list once the CheckBox is triggered and not rebind the list.
View:
<!DOCTYPE html>
<title>SAPUI5</title>
<script src="https://sapui5.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>
<script id="myView" type="ui5/xmlview">
<mvc:View controllerName="MyController" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc"
xmlns:layout="sap.ui.commons.layout">
<Shell>
<Page id="mainPage" showHeader="false">
<FlexBox id="flex" justifyContent="Center" alignItems="Center" direction="Column">
<CheckBox
text="Only 1 option"
selected="{path:'options>/cbx_val'}"
/>
</FlexBox>
</Page>
</Shell>
</mvc:View>
</script>
<body class="sapUiBody">
<div id="content"></div>
</body>
JavaScript:
sap.ui.getCore().attachInit(function() {
"use strict";
sap.ui.controller("MyController", {
onInit: function() {
console.log("INITIALIZING!");
var arr1 = [{
id: "1",
name: "1st option"
}];
var arr2 = arr1.concat([{
id: "2",
name: "2nd option"
}]);
var oModel = new sap.ui.model.json.JSONModel({
cbx_val: false,
arr1: arr1,
arr2: arr2
});
this.getView().setModel(oModel, "options");
var selectVal = new sap.m.Select({
id: "selectField",
selectedKey: '',
editable: true,
enabled: "{= !${options>/cbx_val}}"
});
var selectLbl = new sap.m.Label({
text: "Select:",
labelFor: selectVal,
});
var selectLogicListener = new sap.m.Text({
visible: false,
text: {
parts: ['options>/cbx_val'],
formatter: function(bVal) {
var result = "options>/arr2";
if (bVal) {
result = "options>/arr1";
}
console.log(result);
selectVal.bindItems({
path: result,
template: new sap.ui.core.Item({
key: "{options>id}",
text: "{options>name}"
})
});
}
}
});
this.byId("flex").addItem(selectLbl);
this.byId("flex").addItem(selectVal);
this.byId("flex").addItem(selectLogicListener);
}
});
sap.ui.xmlview({
viewContent: jQuery("#myView").html()
}).placeAt("content");
});

Is it possible to add Binding change event to a component in XML view?

I have a component in SAPUI5 where I need to listen to changes in the binding (Binding.change event). At the moment I'm adding a listener to the Binding in modelContextChange like this:
function onModelContextChange(oEvent){
var oSelect = oEvent.getSource();
var binding = oSelect.getBinding("items");
if(binding){
binding.attachChange(onDataChange, oSelect);
}
}
However this causes all kinds of weird problems, because modelContextChange could be fired multiple times. It would be better to to this in the XML view. I've tried code like this, but it doesn't work.
<Select items="{ path: 'project>/data/', change:'onDataChange' templateShareable: false">
<core:Item key="{project>Id}" text="{project>Parameter}"/>
</Select>
Any recommendations how to do this?
I just came across the problem, too. I solved it in that way:
<Select items="{
path: 'project>/data',
events: {
change: '.onDataChange'
},
templateShareable: false
}">
You can pass an events object to the binding and use the available bindings (e.g. v2.ODataListBinding). Note that you have to use a dot before your function name (.onDataChange). In your controller you can add the function:
onDataChange: function(oEvent) {
// Your implementation...
},
If I remember well from the JS Views, I think it is like this:
<Select items="{ path: 'project>/data/', events: {change:'onDataChange'}, templateShareable: false}">
This is for listening to the Model "change" events.
If you want to listen to the "change" event in the Select control, this is when the user selects a different value in the dropdown, it is like this:
<Select items="{ path: 'project>/data/', templateShareable: false}" change="onDataChange">
EDIT:
Using "modelContextChange" event.
<Select items="{ path: 'project>/data/', templateShareable: false}" modelContextChange="onDataChange">
here is an example
<!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>
<style type="text/css">
.sapMObjLTitle {
cursor: pointer;
}
</style>
<!-- XML-based view definition -->
<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">
<Select change="onDataChange" items="{ path: 'project>/data', templateShareable: false}">
<core:Item key="{project>Id}" text="{project>Parameter}"/>
</Select>
</mvc:View>
</script>
</head>
<body class="sapUiBody">
<div id='content'></div>
</body>
</html>
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/mvc/Controller',
'sap/ui/model/json/JSONModel'
], function(jQuery, Controller, JSONModel) {
var ListController = Controller.extend("myView.Template", {
onInit: function(oEvent) {
var oView = this.getView();
oView.setModel(new JSONModel({
data: [{
Id: "1",
Parameter: "One"
}, {
Id: "2",
Parameter: "Two"
}]
}), "project");
},
onDataChange: function() {
alert("changed")
}
});
return ListController;
});
// Instantiate the View and display
var oView = sap.ui.xmlview({
viewContent: jQuery('#oView').html()
});
oView.placeAt('content');
https://jsbin.com/zufurav/edit?html,js,output
Note: the change attribute in your XML is incorrect
I managed to get the binding change event with this set to the element that I needed by attaching a modelContextChange to the element and handling attaching the change event to the binding in there. Here's the code from the view controller:
modelContextChange: function(oEvent) {
var oElement = oEvent.getSource();
var binding = oElement.getBinding("items");
if (binding) {
//Binding change event could already be attached, detach it first, if it's there
binding.detachChange(this.onBindingChange, oSelect);
binding.attachChange(this.onBindingChange, oSelect);
// Beacause I used this inside a sap.ui.table.Treetable,
// in some cases binding changes occur without the binding change event firing.
// Manually fire the binding change just in case
// YMMV
binding.refresh(true);
}
},
onBindingChange: function() {
//The code that needs to run at binding change
//"this" is set to the correct element
//I specifically needed to add one element in front of other items in a sap.m.Select
var items = this.removeAllItems();
this.addItem(new sap.ui.core.Item({
key: 0,
text: "< Inherit >"
}));
items.forEach(function(item) {
this.addItem(item);
}, this);
}

kendo mvvm binding within a template

I am trying to kendo mvvm bind within a template. Template variables are working but none of the MVVM stuff is.
<div id="list"></div>
<script id="template" type="text/x-kendo-template">
<div>
<button data-bind="visible: alreadyAttending, click: onClick">
Your id is ${ID}
</button>
</div>
</script>
var data = [];
data[0] = { alreadyAttending: true, ID: 1, onClick: function() { alert("Click 1"); }};
data[1] = { alreadyAttending: false, ID: 2, onClick: function() { alert("Click 2"); }};
$("#list").kendoListView({
dataSource: data,
template: kendo.template($("#template").html())
});
Fiddle available here: https://jsfiddle.net/q99ufo3c/5/
You can see the buttons are replaced with values from the data array, but visibility and click events are not wired up. I'm not sure what I'm missing. Does anyone know if this is supported?
You need to define some data attribute to the div element so that Kendo can bind it correctly to your View Model.
data-role="listview" - defines a listview component;
data-template="yourtemplateid" - defines the template to be used;
data-bind="source: dataSource" - defines what is the data
source of the listview component;
In the Javascript you need to have a Model that represents your object that will be in the data source of the list view. I created one called vm and I have chosen to use the ObservableObject extend method because it is useful when you want to create an object with default values, such as the onClick method.
Please, take a look at the Snippet below.
(function() {
var vm = kendo.data.ObservableObject.extend({
init: function(values) {
var defaultValues = {
alreadyAttending: false,
ID: null
};
kendo.data.ObservableObject.fn.init.call(this, $.extend({}, defaultValues, values));
},
onClick: function() {
alert(this.get("ID"));
}
});
var source = [
new vm({
alreadyAttending: true,
ID: 1
}),
new vm({
alreadyAttending: false,
ID: 2
})
];
var mainViewModel = kendo.observable({
dataSource: source
});
kendo.bind($("#list"), mainViewModel);
})();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2016.2.504/js/kendo.all.min.js"></script>
</head>
<body>
<div id="list" data-role="listview" data-template="template" data-bind="source: dataSource"></div>
<script id="template" type="text/x-kendo-template">
<div>
<button data-bind="visible: alreadyAttending, click: onClick">
Your id is #:ID#
</button>
</div>
</script>
</body>
</html>

Extend sap.m.Input: onAfterRendering method doesn't work

I created a custom extension for sap.m.Input. In onAfterRendering I want to mask the value using using jquery-maskmoney as follows:
$('#'+this.getId()+'-inner').maskMoney({ thousands : '', decimal : '.' });'
When I apply mask in the console, everything works fine. But when I try to
add it in the onAfterRendering method, I get some errors when I am trying to setValue:
amountInputControl.setValue(data.amount); // Its is an instance of NumericInput
Error:
TypeError: Cannot read property 'val' of undefined
at sap.m.InputBase._getInputValue (InputBase.js:9)
at sap.m.InputBase.updateDomValue (InputBase.js:32)
at sap.m.InputBase.setValue (InputBase.js:34)
at sap.ui.controller.updateFieldsForReference //Here was executed operation setValue
NumericInput.js
jQuery.sap.declare("control.customInputTypes.NumericInput");
sap.ui.define(['jquery.sap.global', 'sap/m/Input'],
function(jQuery, BaseInput) {
"use strict";
var commonControlInput = BaseInput.extend('control.customInputTypes.NumericInput', /** #lends sap.m.Input.prototype */ {
metadata: {},
renderer : {
render : function(oRm, oControl) {
sap.m.InputRenderer.render(oRm, oControl);
}
}
});
commonControlInput.prototype.onAfterRendering = function () {
$('#'+this.getId()+'-inner').maskMoney({ thousands : '', decimal : '.' });
};
return commonControlInput;
}, /* bExport= */ true);
I didn't even touch the InputBase class, so I wonder whats wrong? If I don't apply this mask everything works fine.
Maybe I cannot use jQuery in the onAfterRendering method of a control?
At first I tought you might want to check sap.m.MaskInput, but I guess that's not exactly what you want...
Anyway, there are a few things I would change in your code. 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 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
<!-- 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"
xmlns:cit="control.customInputTypes">
<cit:NumericInput value="1219999234" />
</mvc:View>
</script>
<script>
sap.ui.getCore().attachInit(function () {
"use strict";
//### Custom Control ###
// remove the first parameter in "real" apps
sap.ui.define("control/customInputTypes/NumericInput",[
"jquery.sap.global",
"sap/m/Input",
"sap/m/InputRenderer"
], function(jQuery, Input, InputRenderer) {
"use strict";
return Input.extend("control.customInputTypes.NumericInput", {
init : function () {
this.addEventDelegate({
onAfterRendering : function(){
var $input = jQuery("#"+this.getId()+"-inner");
$input.maskMoney({
thousands : ".",
decimal : ","
}).maskMoney("mask");
}.bind(this)
});
},
renderer : InputRenderer
});
});
//### Controller ###
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function (Controller) {
"use strict";
return Controller.extend("MyController", {
onInit : function () {
}
});
});
//### 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>

Kendo Grid Custom Reordering

I am using Kendo Grid UI. The following is an example of the same.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="http://cdn.kendostatic.com/2013.3.1324/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.3.1324/styles/kendo.rtl.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.3.1324/styles/kendo.silver.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.3.1324/styles/kendo.dataviz.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2013.3.1324/styles/kendo.dataviz.silver.min.css" rel="stylesheet" />
<link href="/kendo-ui/content/shared/styles/examples.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.1.515/js/kendo.all.min.js"></script>
</head>
<body>
<div id="main">
<h1 id="exampleTitle">
<span class="exampleIcon gridIcon"></span>
<strong>Grid /</strong> Column resizing </h1>
<div id="theme-list-container"></div>
<div id="exampleWrap">
<script>preventFOUC()</script>
<div id="example" class="k-content">
<div id="grid"></div>
<script>
$(document).ready(function() {
gridDataSource = new kendo.data.DataSource({
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
});
$("#grid").kendoGrid({
dataSource: gridDataSource,
scrollable: true,
resizable: true,
columns: [
{
field: "OrderID",
title: "ID"
}, {
field: "OrderDate",
title: "Order Date"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date"
}
]
});
});
</script>
</div>
</div>
</div>
I want a customized reorder on columns. I have disabled drag and drop on OrderID. But columns other than OrderID can be reordered and these columns can be placed before OrderID column.
Is there a way where I can disable dropping of columns before OrderID?
You should do it in two steps:
Disable dropping into first column.
Disable dragging first column.
For the first part after creating the grid you can do:
$("th:nth(0)", "#grid").data("kendoDropTarget").destroy();
This gets from a grid which identifier is grid and the first head cell th:nth(0) the KendoUI DropTarget and destroys it (no longer a valid drop target).
For the second part, you should define a dragstart event that checks that you are dragging the first column and if so, you do not allow to drag it.
$("#grid").data("kendoDraggable").bind("dragstart", function(e) {
if (e.currentTarget.text() === "ID") {
e.preventDefault();
}
});
NOTE: Here I detected the first column asking for its text (ID) but you might change it to check for its position in the list of th in the grid and if so invoke preventDefault.
Check it running here: http://jsfiddle.net/OnaBai/jzZ4u/1/
check this for more elegant implementation:
kendo.ui.Grid.fn._reorderable = function (reorderable) {
return function () {
reorderable.call(this);
var dropTargets = $(this.element).find('th.disable-reorder');
dropTargets.each(function (idx, item) {
$(item).data("kendoDropTarget").destroy();
});
var draggable = $(this.element).data("kendoDraggable");
if (draggable) {
draggable.bind("dragstart", function (e) {
if ($(e.currentTarget).hasClass("disable-reorder"))
e.preventDefault();
});
}
}
}(kendo.ui.Grid.fn._reorderable);
where .disable-reorder class is for disabling column