How do I access the values in the JSON model in my Dialogue list? - sapui5

I have retrieved a JSON model from an ajax call in UI5 but I can't access its members. I have seen examples of people doing something similar but it isn't working for me. Here is my code:
onSumbmitFlowGAkQ: function () {
var oParameters = {
"value": this.getView().byId("flowInputGAK").getValue()
};
$.ajax({
url: "private url",
type: 'POST',
data: JSON.stringify(oParameters),
contentType: 'application/json',
success: function (data) {
this.getView().setModel(new JSONModel(data), "guidedAssistanceGAK");
this.setUpDialog();
}.bind(this),
error: function (e) {
MessageToast.show(e.status);
}
});
setUpDialog: function () {
var lst = new List({
items: {
path: "guidedAssistanceGAK>/flow",
template: new StandardListItem({
title: "{guidedAssistanceGAK>value}",
counter: "{guidedAssistanceGAK>ID}"
})
}
});
var dialog = new Dialog({
title: "choose one",
content: lst,
beginButton: new Button({
text: "OK",
press: function () {
dialog.close();
}
}),
afterClose: function () {
dialog.destroy();
}
});
dialog.open();
//this.oEditor.oRichTextEditor.setValue(this.getView().getModel("guidedAssistanceGAK").getProperty("/flow"));
},
I am using the syntax "guidedAssistanceGAK>/flow" to access the data but it isn't working. I think this is a binding error. I was wondering what would be the right way to do this.

The new dialog doesn't look to be part of the view, which is where your model lives. You could either do this.getView().addDependent(dialog), or you could attach the model to the dialog with dialog.setModel.

Related

Code migration from tinymce 4 to tinymce 5 - problem with action function (true / false)

I have a problem with migrating the plugin from tinymce 4 to tinymka 5. The console tells me "Uncaught (in promise) TypeError: btn.active is not a function"
I can not find an equivalent for tinymce 5. Can someone replace it?
Code below:
tinymce.PluginManager.add('phonelink', function(editor, url) {
// Add a button that opens a window
var linkText = "";
var linkTitle = "";
var link = "";
// tinymce.DOM.loadCSS(url + '/css/phonelink.css');
editor.ui.registry.addButton('phonelink2', {
text: 'asddas',
icon: 'image-options',
onSetup: updateOnSelect,
onAction: onClickPhoneButton
});
// Adds a menu item to the tools menu
editor.ui.registry.addMenuItem('phonelink', {
text: 'asddas',
icon: 'image-options',
context: 'tools',
onAction: onClickPhoneButton,
onSetup: updateOnSelect
});
function onClickPhoneButton(){
editor.windowManager.open({
title: '123213123',
body: {
type: 'panel',
items: [
{type: 'input', name: 'phone', label: 'Teléfono', value: link},
{type: 'input', name: 'showtext', label: 'Texto a mostrar', value: linkText},
{type: 'input', name: 'title', label: 'Título', value: linkTitle}
]
},
buttons: [
{
text: 'Close',
type: 'cancel',
onclick: 'close'
},
{
type: 'submit',
name: 'submitButton',
text: 'Stwórz',
primary: true
}
],
onAction: function(e) {
alert('Toggle menu item clicked');
},
onSubmit: function(e) {
var data = e.getData();
var hrefLink = '<a title="' + data .title + '" href="tel:+34' + data .phone + '">' + data .showtext + '</a>';
if(link !== ''){
editor.setContent(hrefLink);
}else{
editor.insertContent(hrefLink);
}
e.close();
}
});
}
function updateOnSelect() {
var btn = this;
const editorEventCallback = function (e) {
var node = editor.selection.getNode();
var isTelLink = node.href !== undefined && node.href.indexOf('tel:+') !== -1
btn.active(isTelLink);
if(isTelLink){
link = node.href;
link = link.replace("tel:+34", "");
linkTitle = node.title;
linkText = node.text;
}
};
editor.on('NodeChange', editorEventCallback);
return function (btn) {
editor.off('NodeChange', editorEventCallback);
}
}
});
I searched the documentation for a replacement, but found nothing.
TinyMCE 5 no longer passes the button and menu instance via this. Instead it passes an API instance as the first parameter, so you'll want to change your updateOnSelect function to something like this:
function updateOnSelect(api) {
const editorEventCallback = function (e) {
var node = editor.selection.getNode();
var isTelLink = node.href !== undefined && node.href.indexOf('tel:+') !== -1
api.setActive(isTelLink);
if(isTelLink){
link = node.href;
link = link.replace("tel:+34", "");
linkTitle = node.title;
linkText = node.text;
}
};
editor.on('NodeChange', editorEventCallback);
return function (btn) {
editor.off('NodeChange', editorEventCallback);
}
}
You'll note var btn = this has been removed and that the API to set an item as active is setActive instead of active. This can be found in the documentation here: https://www.tiny.cloud/docs/ui-components/typesoftoolbarbuttons/#togglebutton and https://www.tiny.cloud/docs/ui-components/menuitems/#togglemenuitems (see the API section in both links).
In the above, you may have noticed both reference "Toggle" items. That's another change in TinyMCE 5, as different types of buttons/menu items have a separate registration API. So you'll also need to swap to using editor.ui.registry.addToggleButton and editor.ui.registry.addToggleMenuItem. More details about that can be found here if needed: https://www.tiny.cloud/docs/migration-from-4x/#customtoolbarbuttons
Here's an example fiddle showing the changes mentioned above: https://fiddle.tiny.cloud/B5haab.
Hopefully that helps!

sap.m.MenuItem sapui5 attacheventbrowser does not work

trying to attach "onmouseover" event handler to sap.m.MenuItem sapui5 using attachBrowserEvent but I get
Item.attachBrowserEvent is not a function error
here is the code I have tried - Not sure what I am doing wrong.
var item1 = new sap.m.MenuItem({
text: "item1",
press: ()=> {
//do somethign }
});
var item2 = new sap.m.MenuItem({
text: "item2",
enabled: false,
});
item2.attachBrowserEvent("mouseover", function(){
const oPopover = new sap.m.Popover({
showHeader: false,
placement: sap.m.PlacementType.HorizontalPreferredRight,
contentWidth: "500px",
content: [
new sap.m.Text({
text: "item2 is deactived"
})
]
});
item2.attachBrowserEvent("mouseover", function() {
oPopover.openBy(item2);
});
item2.attachBrowserEvent("mouseout", function() {
oPopover.close();
});
});
var oMenu = new sap.m.Menu({
items: [item1,item2]
})
Thats because the control sap.m.MenuItem has no such function. To look up all functions of the controll look in the API: https://sapui5.hana.ondemand.com/1.54.8/#/api/sap.m.MenuItem
BUT a sap.m.MenuItem inherits the function "attachEvent" from sap.ui.base.EventProvider:
https://sapui5.hana.ondemand.com/1.54.8/#/api/sap.ui.base.EventProvider/methods/attachEvent
I think that s what you are looking for.
Hope this is of help to you,
Eric

Protractor-Jasmine2-HTML-Report

I am working on report execution part in Protractor and using Jasmine2 Html Reporter. I am able to generate a report but when my test passes completely without any failure still report shows status as 0.00%. I am not sure why this is happening. I am also attaching the snap shot for the reference.
The code is :
var HtmlReporter = require('protractor-jasmine2-html-reporter');
var reporter = new HtmlReporter({
plugins: [{
package: 'jasmine2-protractor-utils',
showSummary: true,
reportTitle: "Clinicare Report",
filename: 'Clinicarereport.html',
disableHTMLReport: false,//disableHTMLReport
disableScreenshot: false,
captureOnlyFailedSpecs: true,
screenshotPath:'./reports/screenshots',
screenshotOnExpectFailure:true,
screenshotOnSpecFailure:true,
dest: 'protractor-reports',
filename: 'protractor-report.html',
takeScreenshots: true,
ignoreSkippedSpecs: true,
takeScreenshotsOnlyOnFailures: true
// screenshotsFolder: 'F:\\Screeshots'
}]
});
exports.config =
{
directconnect: true,
capabilities: {'browserName': 'chrome'},
framework: 'jasmine',
specs: ['example1.js'],
jasmineNodeOpts: {
defaultTimeoutInterval: 300000
},
onPrepare: function() {
// Add a screenshot reporter and store screenshots to `/tmp/screenshots`:
jasmine.getEnv().addReporter(reporter);
}
}
The spec code is:
var Excel = require('exceljs');
var XLSX = require('xlsx');
var os = require('os');
var TEMP_DIR = os.tmpdir();
var wrkbook = new Excel.Workbook();
describe('Open the clinicare website by logging into the site', function () {
it('Should Add a text in username and password fields and hit login button', function () {
console.log("hello6");
var wb = XLSX.readFile('E:\\Demo\\Generate a test report\\Data_Login.xlsx');
var ws = wb.Sheets.Sheet1;
var json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
console.log("json", json);
//var json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
//console.log("json", json);
for(var a = 0; a < json.length ; a++){
console.log("Test_URL", json[a].Test_URL);
console.log("User_Name", json[a].User_Name);
console.log("Password", json[a].Password);
browser.get(json[a].Test_URL);
//Perform Login:UserName
element(by.model('accessCode')).sendKeys(json[a].User_Name);
//Perform Login:Password
element(by.model('password')).sendKeys(json[a].Password);
//Perform Login:LoginButton
element(by.css('.btn.btn-primary.pull-right')).click();
//Clicking on New Tab
element(by.xpath('/html/body/div[3]/div[1]/div[17]/div/div/table[2]/thead/tr/th[1]/i')).click();
//Clicking on Image for Logout
element(by.css('.user-auth-img.img-circle')).click();
browser.driver.sleep(2000)
//Clicking on LogOut Button
element(by.xpath('/html/body/div[3]/div[1]/div[16]/div[1]/div/div[2]/nav/div[2]/ul/li[4]/ul/li[5]/a/span')).click();
browser.driver.sleep(2000)
//Clicking on Ok for confirmation
element(by.id('logout')).click();
console.log(json[a].User_Name + "Passed the Test");
};
})
});
Try with below spec file it's working fine.
Results you can see
describe("basic test", function () {
beforeAll(function () {
console.log('beforeAll');
});
beforeEach(function () {
console.log('beforeEach');
});
afterAll(function () {
console.log('afterAll');
});
afterEach(function () {
console.log('afterEach');
});
it("Test Case 1: to verify see the global functions hierarchy", function () {
console.log('Sample Test 1');
});
it("Test Case 2: to verify see the global functions hierarchy", function () {
browser.get('http://www.angularjs.org');
element(by.model('todoText')).sendKeys('write a protractor test');
element(by.css('[value="add"]')).click();
var todoList = element.all(by.repeater('todo in todos'));
expect(todoList.count()).toEqual(3);
});
it('should greet the named user', function() {
browser.get('http://www.angularjs.org');
element(by.model('yourName')).sendKeys('Julie');
var greeting = element(by.binding('yourName'));
expect(greeting.getText()).toEqual('Hello Julie!');
});
});

Protractor/Jasmine send REST Call when a test failed

I am using Protractor and Jasmine to test my hybrid mobile app, which works fine. I'd like to create an incident on my Team Foundation Server (TFS), when a test fails. Therefore, I have to send an REST-Call to the Api, which also works fine in my Angular App. But it does not work, when I am inside my test environment.
My Code:
var BrowsePage = require('./browse.page');
var tfsIncident = require('./tfsIncident_service');
var request = require('request');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var specsArray = [];
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
var mappedResult = tfsIncident.create(result);
console.log(mappedResult); //This works so far, but then it crashes
var options = {
method: 'PATCH', //THis Method requiered the API
url: 'MY_COOL_API_ENDPOINT',
headers: {
'Authorization': 'Basic ' + btoa('USERNAME' + ':' + 'PASSWORD'),
'Content-Type': 'application/json-patch+json'
},
body: mappedResult
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response);
console.log(info);
}
}
request(options, callback);
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec);
//This test passes
it('should be able to take display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
// Test is supposed to fail
it('should be able to fail', function () {
expect(browsePage.headline).toBe(1);
});
// Test is supposed to fail as well
it('should be able to fail too', function () {
expect(browsePage.headline).toBe(2);
});
});
So the problem is, that my only console output is (after the console.log(mappedResult)): E/launcher - BUG: launcher exited with 1 tasks remaining
So I have no idea, why this does not work.
Any help appreciated.
Edit
Protractor: 5.0.0
Appium Desktop Client: 1.4.16.1
Chromedriver: 2.27
Windows 10 64 Bit
Jasmine: 2.4.1
I finally got my problem solved. The problem was caused by ignoring the promises by jasmine. I had to add a .controllFlow().wait() to my protractor.promise
The following code works fine:
var BrowsePage = require('./browse.page');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
//Mapping of the result
var incident = [
{
op: 'add',
path: '/fields/System.Title',
value: 'Test: ' + result.fullName + ' failed'
},
{
op: 'add',
path: '/fields/System.Description',
value: result.failedExpectations[0].message
},
{
op: 'add',
path: '/fields/Microsoft.VSTS.Common.Priority',
value: '1'
},
{
op: 'add',
path: '/fields/System.AssignedTo',
value: 'Name Lastname <e#mail.com>'
}
];
protractor.promise.controlFlow().wait(create(incident)).then(function (done) { //The magic happens in this line
console.log("test done from specDone:" + done);
});
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec); //Add new Jasmine-Reporter
function create(incident) {
var request = require('request');
var defer = protractor.promise.defer(); //new promise
request({
url: 'https://MY_COOL_ENDPOINT.COM',
method: "PATCH",
json: true, // <--Very important!!!
headers: {
'Authorization': 'Basic ' + new Buffer('USERNAME' + ':' + 'PASSWORD').toString('base64'),
'Content-Type': 'application/json-patch+json'
},
body: incident
}, function (error, response, body) {
console.log(error);
console.log(response.statusCode);
console.log(body.id); //Id of created incident on TFS
defer.fulfill({
statusCode: response.statusCode
}); //resolve the promise
});
return defer.promise; //return promise here
}
it('should be able to display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
it('should be able to fail', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
it('should be able to fail 2', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
});
Attention
When the test suite is done and the last promise is not resolved at this moment, the last incident is not created. I'll try to work around by adding to the last test a browser.sleep(5000); so that the create(incident) function gets more time to finish.
Thanks to this StackOverflow answer for helping me.

Call function from controller from within event function of a responsivepopup

I have a responsivepopup containing a list in mode 'Delete'.
When I click to delete an item a function is called on press.
Withing this function 'this' is the oList and oEvent.oSource is also the oList.
From within the event function I need to call a function in my controller.
I can't find a way to reference my controller, not even using sap..core..byId("Detail") or even the full namespace.
I tried walking up the elemnt tree from oEvent.oSource.getParent().getParent() to then call .getController() but it's a dead end.
handlePressViewSelection: function(oEvent) {
var oResourceBundle = this.getResourceBundle();
//create the list
var oList = new sap.m.List({
mode: "Delete",
delete: this.handleDeleteSelectionItem
});
oList.setModel(this._oSelectedTrainingsModel);
var oItemTemplate = new sap.m.StandardListItem({
title : "{Title}",
description : "{=${Begda} ? ${Type} - { path: 'Begda', type: 'sap.ui.model.type.Date', formatOptions: { style: 'medium' }} : ${Type}}",
icon : "{icon}",
iconInset : false
});
oList.bindAggregation("items", {
path: "/",
template: oItemTemplate,
type: "Active"
});
var oBeginButton = new sap.m.Button({
text: "Action1",
type: sap.m.ButtonType.Reject,
press: function(){
oResponsivePopover.setShowCloseButton(false);
}
});
var oEndButton = new sap.m.Button({
text: "Action2",
type: sap.m.ButtonType.Accept,
press: function(){
oResponsivePopover.setShowCloseButton(true);
}
});
var oResponsivePopover = new sap.m.ResponsivePopover({
placement: sap.m.PlacementType.Bottom,
title: "",
showHeader: false,
beginButton: oBeginButton,
endButton: oEndButton,
horizontalScrolling: false,
content: [
oList
]
});
oResponsivePopover.openBy(oEvent.oSource);
},
handleDeleteSelectionItem: function(oEvent) {
var oListItem = oEvent.getParameter('listItem');
var oList = oListItem.getParent();
var path = oListItem.getBindingContext().sPath;
oList.getModel().getData().splice(parseInt(path.substring(1)), 1);
oList.removeItem(oEvent.getParameter('listItem'));
oList.getParent().getParent().getController()._updateViewSelectionButtonText(); //--> BROKEN
},
When you instantiate your popup from a fragment, you can specify "a Controller to be used for event handlers in the Fragment" (see https://sapui5.hana.ondemand.com/#docs/api/symbols/sap.ui.html#.xmlfragment)
For example:
onOpenResponsivePopover : function(oEvent) {
if (!this._oResponsivePopover) {
// adding 'this' makes sure you specify the current controller to be used for event handlers
this._oResponsivePopover = sap.ui.xmlfragment("namespace.to.your.popoverfragment", this);
this.getView().addDependent(this._oResponsivePopover);
}
this._oResponsivePopover.openBy(oEvent.getSource());
},