addEventListener() question/weird behavior - ajax

I'm developing a game for Facebook. I'm using PHP and FBJS. I'm using addEventListener() to attach events to two buttons. Each button has it's own event handler which is a js function. The first event handler (loadNewCargo()) gets called with no problems. But the second event handler (discardExistingCargo()) causes the page to refresh when it is called. The examples I've seen use a single event handler function for multiple elements. I'm creating one handler for each element. Is this illegal? Here's the code ('load-new-submit' and 'discard-existing-submit' are the IDs for the two buttons on the dialog):
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', loadNewCargo);
/**/
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', discardExistingCargo);
/**/
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
dialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
dialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
function loadCargoEventHandler(evt) {
if(evt.type == 'click') {
var dialog = new Dialog().showChoice('Load Cargo', fbjs_load_cargo_select, 'Minimize', 'Pass');
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
dialog.hide();
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
var actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
dialog.oncancel = function() {
moveTrainManual();
}
}
}
function loadNewCargo(evt) {
//new Dialog().showMessage('loadNewCargo', 'city id='+cityId+', train id='+trainId);
//debugger;
cityId = evt.target.cityId;
trainId = evt.target.trainId;
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Load new goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
openCargoHolds = data.openCargoHolds;
cargoHoldsUsed = 0;
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'cityGoods': data.cityGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
//debugger;
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Load cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-new', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-new-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
}
function discardExistingCargo(evt) {
//new Dialog().showMessage('loadNewCargo', 'city id='+cityId+', train id='+trainId);
cityId = evt.target.cityId;
trainId = evt.target.trainId;
/**/
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Discard existing goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'trainGoods': data.trainGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
var dialog = new Dialog().showChoice('Discard Cargo', fbjsData, 'Discard cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-discard', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-discard-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
/**/
}
Thank you for any assistance you can offer.

You can return false; from the discardExistingCargo function to avoid the default submit action - which is causing the page to refresh.

Problem solved: the button's input type was "submit", hence the page refresh (doh!)

Related

Multiple People Picker Columns (fields) on one form

SharePoint Online: I have multiple people picker columns and enter in a number of places people. I get the people OK but it won't update. It says it the entry is undefined. I thought maybe separating each out would work but obviously not. I hope I get some help on this one. What I want to do is to allow users to enter names into where the div entries are and as a people picker. I accomplished that but when you submit the form it says that any entry other than the first is undefined.
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" > < /script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript" src="/_layouts/15/autofill.js"></script>
<script type="text/javascript" src="/_layouts/15/1033/sts_strings.js"></script>
<script type="text/javascript">
var prim5 = 0;var sec4 = 0;var auth5 = 0;
var EorB25 = "";var BorE25 = "";var BorE35 = "";var siteUrl = "https://sp-cloud.kp.org/sites/MedicaidRepository";var cat25 = "";var regimpact = "";var regimpact1 = "";var prim25="";var sec25="";
var auth25="";var s1 = "";var soxD1 = "";var k1 = 'No';var com2 = "";var sDate1 = "";var sSever = "";var kDate1 = "";var finalusersP = [];var finalusers22 = [];var finalusersK = [];var user22 = [];var userK = [];var userP = [];var users22 = [];var usersK = [];var usersP = [];var userPemail = "";var userKemail = "";var user22email = "";
var tDay = new Date();
var dd = tDay.getDate();
var mm = tDay.getMonth()+1;
var yy = tDay.getFullYear();
var sDate = mm+ '/' +dd+ '/' +yy;
$(document).ready(function() {
prim5 = 1;
initializePeoplePickerP('peoplePickerDivP');
registerPPOnChangeEventP($('#peoplePickerDivP'));
});
$(document).ready(function() {
sec5 = 1;
initializePeoplePickerS('peoplePickerDivS');
registerPPOnChangeEventS($('#peoplePickerDivS'));
});
$(document).ready(function() {
auth5 = 1;
initializePeoplePickerK('peoplePickerDivK');
registerPPOnChangeEventK($('#peoplePickerDivK'));
});
function initializePeoplePickerP(peoplePickerElementIdP, UsersP) {
if (typeof(UsersP) == 'undefined') UsersP = null;
console.log('UsersP: ' +UsersP);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdP, null, schema);
}
function initializePeoplePickerS(peoplePickerElementIdS, Users22) {
if (typeof(Users22) == 'undefined') Users22 = null;
console.log('Users22: ' +Users22);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdS, null, schema);
}
function initializePeoplePickerK(peoplePickerElementIdK, UsersK) {
if (typeof(UsersK) == 'undefined') UsersK = null;
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdK, null, schema);
}
function registerPPOnChangeEventP(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
//var ppidTest = picker.toString();
console.log("picker: " +picker);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoP();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventS(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers22').html("");
$('#user22Keys').html("");
$('#user22ProfileProperties').html("");
$('#user22ID').html("");
} else {
setTimeout(function () {
getUserInfoS();
},
100);
}
picker.oldChanged();
}
} else {
//setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventK(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoK();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
// Query the picker for user information.
var userPropertyP = "";
var userPropertyS = "";
var userPropertyK ="";
var userPemail = "";
var i = 0;
var j = 0;
var m = 0;
var keysP = "";
var keysS = "";
var keysK = "";
function getUserInfoP() {
// Get the people picker object from the page.
var peoplePickerP = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivP_TopSpan;
// Get information about all users.
var usersP = peoplePickerP.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersP = new Array();
console.log('Users: ' +usersP);
var ownerP = usersP[0];
for(i = 0; i < usersP.length; i++){
userPemail = usersP[i];
}
console.log('Owner: ' +ownerP);
$("#siteOwenerEmail").val(ownerP.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerP.Key);
$("#siteOwnerName").val(ownerP.DisplayText);
$("#siteOwnerLogin").val(ownerP.Description);console.log('Get People Picker NameP: ' +ownerP.DisplayText);
var userInfo = '';
if(prim5 > 0){
for (var i = 0; i < usersP.length; i++) {
userP = usersP[i];
if(userP !== null){
//userPemail = userP.EntityData.Email;
userPemail = ownerP.DisplayText;
}
console.log("userPemail: " +userPemail);
return userPemail;
console.log('i= ' +i+ 'User= ' +userP);
for (userPropertyP in userP) {
prim25 += userPropertyP + ': ' + userP[userPropertyP] + '<br>';
}
}
$('#resolvedUsers').html(prim25);
// Get user keys.
keysP = peoplePickerP.GetAllUserKeys();
$('#userKeys').html(keysP);
// Get the first user's ID by using the login name.
getUserIdP(usersP[0].Key);
console.log('Initial: ' +prim25);
}
}
function getUserInfoS() {
// Get the people picker object from the page.
var peoplePickerS = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivS_TopSpan;
// Get information about all users.
users22 = peoplePickerS.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersS = new Array();
console.log('Users: ' + users22);
var ownerS = users22[0];
/*for(i = 0; i < usersS.length; j++){
userSemail = usersS[i];
}*/
console.log('Owner: ' +ownerS);
$("#siteOwenerEmail").val(ownerS.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerS.Key);
$("#siteOwnerName").val(ownerS.DisplayText);
$("#siteOwnerLogin").val(ownerS.Description);console.log('Get People Picker NameS: ' +ownerS.DisplayText);
var userInfo = '';
if(sec4 > 0){
for (j = 0; j < users22.length; j++) {
user22 = users22[j];
if(user22 !== null){
//userPemail = userP.EntityData.Email;
user22email = ownerS.DisplayText;
}
for (userPropertyS in user22) {
sec25 += userPropertyS + ': ' + user22[userPropertyS] + '<br>';
}
}
$('#resolvedUsers').html(sec25);
// Get user keys.
keysS = peoplePickerS.GetAllUserKeys();
$('#user22Keys').html(keysS);
// Get the first user's ID by using the login name.
getUserIdS( users22[0].Key);
}
}
function getUserInfoK() {
// Get the people picker object from the page.
var peoplePickerK = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivK_TopSpan;
// Get information about all users.
usersK = peoplePickerK.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersK = new Array();
console.log('Users: ' +usersK);
var ownerK = usersK[0];
/*for(i = 0; i < usersK.length; i++){
userKemail = usersK[i];
}*/
console.log('Owner: ' +ownerK);
$("#siteOwenerEmail").val(ownerK.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerK.Key);
$("#siteOwnerName").val(ownerK.DisplayText);
$("#siteOwnerLogin").val(ownerK.Description);console.log('Get People Picker NameK: ' +ownerK.DisplayText);
var userInfo = '';
if(auth5 > 0){
for (m = 0; m < usersK.length; m++) {
userK = usersK[m];
if(userK !== null){
//userPemail = userP.EntityData.Email;
userKemail = ownerK.DisplayText;
}
for (userPropertyK in userK) {
auth25 += userPropertyK + ': ' + userK[userPropertyK] + '<br>';
}
}
$('#resolvedUsers').html(auth25);
// Get user keys.
keysK = peoplePickerK.GetAllUserKeys();
$('#userKeys').html(keysK);
// Get the first user's ID by using the login name.
getUserIdK(usersK[0].Key);
}
}
// Get the user ID.
function getUserIdP(loginName) {
console.log('Get User ID-P');
var context = new SP.ClientContext.get_current();
this.userP = context.get_web().ensureUser(loginName);
context.load(this.userP);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessP),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessP() {
$('#userId').html(this.userP.get_id());
$("#siteOwenerId").val(this.userP.get_id());
userP = $("#siteOwenerId").val(this.userP.get_id());
}
function getUserIdS(loginName) {
console.log("Get User ID-S");
var context = new SP.ClientContext.get_current();
this.user22 = context.get_web().ensureUser(loginName);
context.load(this.user22);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessS),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessS() {
$('#userId').html(this.user22.get_id());
$("#siteOwenerId").val(this.user22.get_id());
userS = $("#siteOwenerId").val(this.user22.get_id());
}
function getUserIdK(loginName) {
console.log('Get User ID-K');
var context = new SP.ClientContext.get_current();
this.userK = context.get_web().ensureUser(loginName);
context.load(this.userK);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessK),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessK() {
$('#userId').html(this.userK.get_id());
$("#siteOwenerId").val(this.userK.get_id());
userK = $("#siteOwenerId").val(this.userK.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}
function addNewIntake(){
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',updateListItem1);
}
function updateListItem1() {
finalusersP.push(SP.FieldUserValue.fromUser(userP.Key));
finalusers22.push(SP.FieldUserValue.fromUser(user22.Key));
finalusersK.push(SP.FieldUserValue.fromUser(userK.Key));
var clientContext = new SP.ClientContext(siteUrl);
var oList =
clientContext.get_web().get_lists().getByTitle('Issue_Tracker_List');
this.oListItem = oList.addItem();
//console.log('primary person info: ' + finalusersP);
oListItem.set_item('MainContact2',finalusersP);
if(finalusers22 !== ""){
//console.log('secondary person info: ' +finalusers22);
oListItem.set_item('AdditionalContact_x0028_s_x0029_',finalusersS);
}
if(finalusersK !== ""){
oListItem.set_item('ITSupportOwner',finalusersK);
}
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById('main12').style.display="none";
document.getElementById('main22').style.display="block";
setTimeout(CloseDlg, 2000);
}
function CloseDlg() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Dynamics on prem 8.2 getGlobalContext doesn't work only Xrm.Page.Context works

I want to show the "Run Workflow" ribbon button only to users with system administrator so I use the following JS which work fine in my Dynamics solution:
function getrolesarray(formcontextfromribbon) {
var Globalcontext = Xrm.Page.context;
var strFirstThree = Globalcontext.getVersion().substring(0, 3);
var sameunit = true;
var noclosed_status = true;
var selview = 0;
var roleid = Globalcontext.getUserRoles();
var RoleName_concat = "";
var user_sysadmin_yesno = false;
var name;
for (var i = 0; i < roleid.length; i++) {
var roleID = roleid[i];
var RoleName = getRoleName_XMLHttp(roleID,strFirstThree);
RoleName = RoleName.toUpperCase()
if ((RoleName == 'SYSTEM ADMINISTRATOR')) {
user_sysadmin_yesno = true;
break;
}
}
return user_sysadmin_yesno;
}
function getRoleName_XMLHttp(roleID,strFirstThree) {
var roleName = null;
var param = roleID.toString().replace("{", "").replace("}", "");
var ajaxurl = Globalcontext.getClientUrl() + "/api/data/v" + strFirstThree + "/roles(" + param + ")?$select=_businessunitid_value,name,roleid";
var req = new XMLHttpRequest();
req.open("GET", ajaxurl, false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response);
var _businessunitid_value = result["_businessunitid_value"];
var _businessunitid_value_formatted = result["_businessunitid_value#OData.Community.Display.V1.FormattedValue"];
var _businessunitid_value_lookuplogicalname = result["_businessunitid_value#Microsoft.Dynamics.CRM.lookuplogicalname"];
var name = result["name"];
var roleid = result["roleid"];
roleName = result["name"];
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
return roleName;
}
If I try to update the deprecated form using the following on line 2:
var Globalcontext = Xrm.Utility.getGlobalContext();
It will return undefined, how to make it work?
Open CRM, open developer tools (by clicking F12), choose "Console", enter Xrm.Utility in the console, hit enter, expand the object you get and check if the getGlobalContext extension is there.
Upon inspection I found it was not present, and must only be available for version 9.0 and above.

nativescript: new object is not an new an empty opject

As example only.
I have:
var ListingModel = require("~/shared/view-models/listing-view-model");
function listing10(){
var Listing = new ListingModel.ListingViewModel();
Listing.horizontalAddData('10');
frameModule.topmost().navigate("/views/listing/list");
}
function listing20(){
var Listing = new ListingModel.ListingViewModel();
Listing.horizontalAddData('20');
frameModule.topmost().navigate("/views/listing/list");
}
function listing50(){
var Listing = new ListingModel.ListingViewModel();
Listing.horizontalAddData('50');
frameModule.topmost().navigate("/views/listing/list");
}
exports.listing10 = listing10;
exports.listing20 = listing20;
exports.listing50 = listing50;
When i now tap on event listing10 i receive all information which i require.
But, when i now tap event listing20 i become back the information from listing10 and listing20. That means, the the new object isnt a new object with cleared data?
Question: How i must call the new ListingModel.ListingViewModel(); so that i really become back a new, clear ListingViewModel Object?
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Model = require('~/shared/view-models/view-model');
var ListingViewModel = (function (_super) {
__extends(ListingViewModel, _super);
function ListingViewModel() {
_super.apply(this, arguments);
}
var params = {start: 0 , limit: 7};
var page = 0;
var _listRequested = new virtualArray.VirtualArray(7);
_listRequested.loadSize = params.limit;
var _fetch = new f.fetchHelper();
var loading = 0;
var that=this;
var indexes = [];
var horizontalindex = [];
var fetchlist = [];
var listing ='';
Object.defineProperty(ListingViewModel.prototype, "list", {
get: function () {
return _listRequested;
},
enumerable: true,
configurable: true
});
ListingViewModel.prototype.horizontalAddData = function(val) {
listing = val;
that.loadItems();
};
loadItems = function (args) {
if(loading == 1) return;
loading = 1;
fetchlist = [];
var url = config.apiUrl + '?t=listing'
+ '&listing=' + list
+ '&start=' + params.start
+ '&limit=' + params.limit;
_fetch.getJSON(url).then(function (res) {
try {
for (var i = 0; i < res.list.length; i++) {
var am = new Model.Model(res.list[i]);
fetchlist.push(am);
}
_listRequested.length = _listRequested.length + fetchlist.length;
_listRequested.load(params.start, fetchlist);
} catch (e) {
alert('error' + e);
}
params.start = params.start + params.limit;
loading = 0;
});
};
return ListingViewModel;
})(observable.Observable);
exports.ListingViewModel = ListingViewModel;

leaflet Dynamic icon with filter

I'm trying to create an map with the leaflet-simple-csv-master (i'm a beginner). It's really nice and i'd like to show different icons with my types (for exemple 1 icon for schools, one for administrations,...). I succed to show my different icons when i have the map but when i click to the filter, my icons disappear. In fact it doesn't work because it do not recognize my variable when i use the filter and i can read that my img is no more logos/type1.png but logos/undefined.png.
This is my all code.
var basemap = new L.TileLayer(baseUrl, {maxZoom: 17, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});
var center = new L.LatLng(0, 0);
var map = new L.Map('map', {center: center, zoom: 2, maxZoom: maxZoom, layers: [basemap]});
var popupOpts = {
autoPanPadding: new L.Point(5, 50),
autoPan: true
};
var points = L.geoCsv (null, {
firstLineTitles: true,
fieldSeparator: fieldSeparator,
onEachFeature: function (feature, layer) {
var popup = '<div class="popup-content"><table class="table table-striped table-condensed">';
for (var clave in feature.properties) {
var title = points.getPropertyTitle(clave).strip();
var attr = feature.properties[clave];
if (title == labelColumn) {
layer.bindLabel(feature.properties[clave], {className: 'map-label'});
}
if (attr.indexOf('http') === 0) {
attr = '<a target="_blank" href="' + attr + '">'+ attr + '</a>';
}
if (attr) {
popup += '<tr><th>'+title+'</th><td>'+ attr +'</td></tr>';
}
}
popup += "</table></popup-content>";
layer.bindPopup(popup, popupOpts);
},
pointToLayer: function (feature, latlng) {
var logo = feature.properties['type'];
return L.marker(latlng, {
icon:L.icon({
iconUrl: 'logos/'+logo+'.png',
shadowUrl: 'marker-shadow.png',
iconSize: [25,41],
shadowSize: [41, 41],
shadowAnchor: [13, 20]
})
});
},
filter: function(feature, layer) {
total += 1;
if (!filterString) {
hits += 1;
return true;
}
var hit = false;
var lowerFilterString = filterString.toLowerCase().strip();
$.each(feature.properties, function(k, v) {
var value = v.toLowerCase();
if (value.indexOf(lowerFilterString) !== -1) {
hit = true;
hits += 1;
return false;
}
});
return hit;
}
});
var hits = 0;
var total = 0;
var filterString;
var markers = new L.MarkerClusterGroup();
var dataCsv;
var addCsvMarkers = function() {
hits = 0;
total = 0;
filterString = document.getElementById('filter-string').value;
if (filterString) {
$("#clear").fadeIn();
} else {
$("#clear").fadeOut();
}
map.removeLayer(markers);
points.clearLayers();
markers = new L.MarkerClusterGroup(clusterOptions);
points.addData(dataCsv);
markers.addLayer(points);
map.addLayer(markers);
try {
var bounds = markers.getBounds();
if (bounds) {
map.fitBounds(bounds);
}
} catch(err) {
// pass
}
if (total > 0) {
$('#search-results').html("Showing " + hits + " of " + total);
}
return false;
};
var typeAheadSource = [];
function ArrayToSet(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populateTypeAhead(csv, delimiter) {
var lines = csv.split("\n");
for (var i = lines.length - 1; i >= 1; i--) {
var items = lines[i].split(delimiter);
for (var j = items.length - 1; j >= 0; j--) {
var item = items[j].strip();
item = item.replace(/"/g,'');
if (item.indexOf("http") !== 0 && isNaN(parseFloat(item))) {
typeAheadSource.push(item);
var words = item.split(/\W+/);
for (var k = words.length - 1; k >= 0; k--) {
typeAheadSource.push(words[k]);
}
}
}
}
}
if(typeof(String.prototype.strip) === "undefined") {
String.prototype.strip = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
map.addLayer(markers);
$(document).ready( function() {
$.ajax ({
type:'GET',
dataType:'text',
url: dataUrl,
contentType: "text/csv; charset=utf-8",
error: function() {
alert('Error retrieving csv file');
},
success: function(csv) {
dataCsv = csv;
populateTypeAhead(csv, fieldSeparator);
typeAheadSource = ArrayToSet(typeAheadSource);
$('#filter-string').typeahead({source: typeAheadSource});
addCsvMarkers();
}
});
$("#clear").click(function(evt){
evt.preventDefault();
$("#filter-string").val("").focus();
addCsvMarkers();
});
});

Scroll Events in TouchGridPanel

I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}

Resources