-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXrmShortcuts.js
More file actions
540 lines (501 loc) · 22.7 KB
/
XrmShortcuts.js
File metadata and controls
540 lines (501 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/// <reference path="XrmPage-vsdoc.js" />
// Shorthand XRM Library with Chaining
var ShorthandXrmConstants = {
///<summary>A set of XRM constants - i.e. requirement levels, mandatory level etc.</summary>
requirementLevels: {
required: "required",
none: "none",
recommended: "recommended"
},
submitModes: {
always: "always",
never: "never"
},
attributeTypes: {
datetime: "datetime",
boolean: "boolean",
decimal: "decimal",
double: "double",
integer: "integer",
lookup: "lookup",
memo: "memo",
money: "money",
optionset: "optionset",
string: "string"
},
formTypes: {
Create: 1,
Update: 2,
ReadOnly: 3,
Disabled: 4,
QuickCreate: 5, //deprecated
BulkEdit: 6,
ReadOptimized: 11
},
saveModes: {
Save: 1,
SaveAndClose: 2
}
}
$c = ShorthandXrmConstants;
function ShorthandXrmUtilities() {
///<summary>Utility library</summary>
var RequiredFields = [];
var that = this; // does it matter where this goes?
function debugAttributes() {
Xrm.Page.ui.controls.forEach(function (control, index) {
var controlType = control.getControlType();
that.writeToConsole(control.getName() + " - " + control.getControlType());
});
};
function getRequiredAttributes() {
for (var x = 0; x < RequiredFields.length; x++) {
Xrm.Page.getAttribute(RequiredFields[x]).removeOnChange(this.notifyRequiredAttributes);
Xrm.Page.ui.clearFormNotification(RequiredFields[x]);
}
RequiredFields = [];
Xrm.Page.ui.controls.forEach(function (control, index) {
var controlType = control.getControlType();
if (controlType != "iframe" && controlType != "webresource" && controlType != "subgrid") {
if (control.getVisible()) {
var attribute = control.getAttribute();
if (attribute != null) {
var req = attribute.getRequiredLevel();
if (req == "required") {
// control.setNotification("Fill me in");
var name = attribute.getName();
if (RequiredFields.indexOf(name) < 0) {
RequiredFields.push(name);
//attribute.addOnChange(this.notifyRequiredAttributes);
attribute.addOnChange(that.notifyRequiredAttributes);
// console.log(name);
// Xrm.Page.getControl(name).setNotification("Fill me in");
}
}
}
}
}
});
};
this.notifyRequiredAttributes = function () {
getRequiredAttributes();
var notification = "";
for (var i = 0; i < RequiredFields.length; i++) {
var field = RequiredFields[i];
var attribute = Xrm.Page.getAttribute(field);
var val;
if (attribute.getAttributeType() != "optionset")
val = Xrm.Page.getAttribute(field).getValue(); // this sometimes fails...
else val = Xrm.Page.getAttribute(field).getText();
// brc_enquirytype,brc_serviceid,new_sectorid,statecode,new_requeststatus,new_requeststatusreason,new_actiontaken
if (!val || val == "") {
var label = Xrm.Page.getControl(field).getLabel();
notification += label + " is required; ";
Xrm.Page.ui.setFormNotification(label + " is required ", 'INFO', field);
}
else
Xrm.Page.ui.clearFormNotification(field);
}
};
this.writeCurrentIdToConsole = function () {
this.writeToConsole(Xrm.Page.data.entity.getId());
};
this.compareGuids = function (guid1, guid2) {
///<summary>Compares two guids. Converts both to lower case and strips braces. If both are null, will return true</summary>
if (guid1 && guid2) {
guid1 = guid1.replace("{", "").replace("}", "").toLowerCase();
guid2 = guid2.replace("{", "").replace("}", "").toLowerCase();
if (guid1 == guid2)
return true;
else
return false;
}
else {
// if either has some kind of value, return false - otherwise both null, so return true
return
(!guid1 && guid2) ? false :
(gui1 && !guid2) ? false :
true;
}
};
this.writeToConsole = function (message, level) {
///<summary>if a console is available in the browser, write to it. Can specify the alert level</summary>
///<param name="message">String</param>
///<param name="level">Type as string: Error, Warning, Info, Default or none</param>
if (typeof console != 'undefined') {
if (level) {
switch (level.toLowerCase()) {
case "error":
console.error(message);
break;
case "warning":
console.warn(message);
break;
case "info":
console.info(message);
break;
default:
console.log(message);
break;
}
}
else
console.log(message);
}
};
this.addOnSave = function (onSaveFunction) {
Xrm.Page.data.entity.addOnSave(onSaveFunction);
};
this.confirmDialog = function (message, yesCloseCallback, noCloseCallback) {
Xrm.Utility.confirmDialog(message, yesCloseCallback, noCloseCallback);
};
this.tidyGuid = function (guid) {
///<summary>Returns a guid in lowercase with no brackets</summary>
if (guid) {
return guid.replace("{", "").replace("}", "").toLowerCase();
}
};
this.hideSubGridOpenAssociatedView = function (gridName) {
document.getElementById(gridName + "_openAssociatedGridViewImageButton").style.visibility = 'hidden';
};
this.hideSubGridAddButton = function (gridName) {
///<summary>UNSUPPORTED: Hides the + button on sub grids. Uses unsupported getElementById</summary>
// ServiceAssessments
document.getElementById(gridName + "_addImageButton").style.visibility = 'hidden';
};
this.getLookupName = function (attribute) {
///<summary>Returns the text value from a lookup field, or a blank string if it is null</summary>
///<param name="lookupVal" type="XrmTypes.Attribute">Lookup value</param>
///<returns type="String"></returns>
var lookup = Xrm.Page.getAttribute(attribute).getValue();
return (lookup != null && lookup.length > 0 & lookup != "null") ? lookup[0].name : "";
};
this.getLookupId = function (attribute) {
///<summary>Returns the ID value from a lookup field, or a null</summary>
///<param name="attribute" type="Page Attribute ID">Attribute ID</param>
///<returns type="ID as String or null"></returns>
var lookup = Xrm.Page.getAttribute(attribute).getValue();
return (lookup != null && lookup.length > 0 & lookup != "null") ? lookup[0].id.toLowerCase() : null;
};
this.setVisibleTabSection = function (tabname, sectionname, show) {
///<summary>Sets visibility of a tab.\nThe sectionname can be null.</summary>
var tab = Xrm.Page.ui.tabs.get(tabname);
if (tab !== null) {
if (sectionname === null)
tab.setVisible(show);
else {
var section = tab.sections.get(sectionname);
if (section !== null) {
section.setVisible(show);
if (show)
tab.setVisible(show);
}
}
}
else {
// alert("?");
}
};
this.sectionControls = function (tabname, sectionname) {
///<summary>returns a collection of controls for a section</summary>
var tab = Xrm.Page.ui.tabs.get(tabname);
if (tab !== null) {
var section = tab.sections.get(sectionname);
if (section !== null) {
return section.controls.get();
}
}
return null;
};
this.CheckUserRole = function (roleName, context) {
var userHasRole = false;
//get the current roles for the user
var userRoles = context.getUserRoles();
//get the roleids with the rolename
//the roleids can be multiple for multiple business units
var roleIdArray = this.FetchUserRoleIdWithName(roleName, context);
for (var userRole in userRoles) {
if (jQuery.inArray(userRoles[userRole], roleIdArray) != -1) {
userHasRole = true;
break;
}
}
return userHasRole;
};
this.setFormNotification = function (message, level, uniqueId) {
///<summary>2013: Displays form level notification. If using an attribute, use $x(attribute_name).setFormNotificationfunction</summary>
///<param name="message">String: The text of the message </param>
///<param name="level">Type: ERROR, WARNING, INFO</param>
///<param name="uniqueId">uniqueId: An ID for the notification.</param>
Xrm.Page.ui.setFormNotification(message, level ? level : "INFO", uniqueId);
};
this.clearFormNotification = function (uniqueId) {
///<summary>2013: Clears a form level notification</summary>
Xrm.Page.ui.clearFormNotification(uniqueId);
};
this.getUserId = function () {
return Xrm.Page.context.getUserId();
};
this.getUserName = function () {
return Xrm.Page.context.getUserName();
};
this.getFormType = function () {
return Xrm.Page.ui.getFormType();
};
this.getFormRecordGuid = function () {
return Xrm.Page.data.entity.getId();
};
// Parameters
// save => A Boolean value to indicate if data should be saved after it is refreshed.
// successCallback => A function to call when the operation succeed
// errorCallbak => A function to call when the operation fails. It gets called with 2 parameters (an error code and a localized error message)
this.refresh = function (save, successCallback, errorCallback) {
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
};
// Parameters
// successCallback => A function to call when the operation succeed
// errorCallbak => A function to call when the operation fails. It gets called with 2 parameters (an error code and a localized error message)
this.save = function (successCallback, errorCallback) {
Xrm.Page.data.save().then(successCallback, errorCallback);
};
// Checks whether the security role exists in the system by using ODATA call
this.FetchUserRoleIdWithName = function (roleName, context) {
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataUri = serverUrl + "/XRMServices/2011/OrganizationData.svc/RoleSet?$filter=Name eq '" + roleName + "'&$select=RoleId";
var jSonArray = new Array();
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataUri,
async: false,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null) {
for (var count = 0; count < data.d.results.length; count++) {
jSonArray.push(data.d.results[count].RoleId);
}
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error : has occured during retrieval of the role " + roleName);
}
});
return jSonArray;
};
// compare two arrays - note JSON data can't be compared in here
this.compareArrays=function(array1, array2){
// if the either array is a falsy value, return
if (!array1 || !array2) {
return false;
}
// compare lengths - can save a lot of time
if (array1.length != array2.length) {
return false;
}
for (var i = 0, l = array1.length; i < l; i++) {
// Check if we have nested arrays
if (array1[i] instanceof Array && array2[i] instanceof Array) {
// recurse into the nested arrays
//if (!this[i].equals(array[i]))
if(!this.compareArrays(array1[i], array2[i]))
return false;
}
else if (array1[i] != array2[i]) {
// console.log("value different");
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
//Retrieve Querystring Parameter
this.getQSParm = function (parameter) {
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split('&');
for (var i = 0; i < arr.length; i++) {
// splits each of field-value pair
var index = arr[i].indexOf('=');
var key = arr[i].substring(0, index);
var val = arr[i].substring(index + 1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
return arrQrStr[parameter] === null ? "" : decodeURIComponent(arrQrStr[parameter]);
}
//Set Field to Lookup SearchText
this.searchTextToAttribute = function (attribute) {
Xrm.Page.getAttribute(attribute).setValue($u.getQSParm('_searchText'));
}
}
var $u = new ShorthandXrmUtilities();
var ShorthandXRM = function (attribute) {
///<summary>
///Shortcut library for various Xrm.Page functions. If there are no return values, chaining is enabled.\n
///Can maybe split into data manipulation and attribute/control manipulation tools
///</summary>
// Utility Stuff
// addCustomFilter ?
this.addOnChange = function (functionToCall) {
/// <summary>Add an onchange function to a field</summary>
Xrm.Page.getAttribute(attribute).addOnChange(functionToCall);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.removeOnChange = function (functionToRemove) {
Xrm.Page.getAttribute(attribute).removeOnChange(functionToRemove);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.switchVisible = function () {
///<summary>Inverts the visbility of a control</summary>
var isVisible = Xrm.Page.getControl(attribute).getVisible();
Xrm.Page.getControl(attribute).setVisible(!isVisible);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.clearNotification = function () {
///<summary>2013: Clears a notification on an attribute</summary>
Xrm.Page.getControl(attribute).clearNotification();
return new ShorthandXRM(attribute);
};
this.addPreSearch = function (preSearchFunction) {
///<summary>2013: Adds pre trigger filter to the lookup</summary>
Xrm.Page.getControl(attribute).addPreSearch(preSearchFunction);
return new ShorthandXRM(attribute);
};
this.removePreSearch = function(preSearchFunction){
///<summary>2013: Removes pre trigger filter to the lookup</summary>
Xrm.Page.getControl(attribute).removePreSearch(preSearchFunction);
return new ShorthandXRM(attribute);
};
this.clearFormNotification = function () {
Xrm.Page.ui.clearFormNotification(attribute);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.fireOnChange = function () {
Xrm.Page.getAttribute(attribute).fireOnChange();
return new ShorthandXRM(attribute);
};
// Getters
this.getValue = function () {
///<summary>Returns the attribute value. Can't be chained</summmary>
return Xrm.Page.getAttribute(attribute).getValue();
};
this.getLookupGuidValue = function () {
///<summary>Returns the attributes GUID value with braces, or NULL. Can't be chained</summmary>
var field = Xrm.Page.getAttribute(attribute);
if (field) {
var lookup = field.getValue();
return (lookup != null && lookup.length > 0 & lookup != "null") ? lookup[0].id.toLowerCase() : null;
}
else
return null;
};
this.getVisible = function () {
return Xrm.Page.getControl(attribute).getVisible();
};
this.getText = function () {
///<summary>Returns the string value for the currently select option set (and null if none) Does not chain</summary>
return Xrm.Page.getAttribute(attribute).getText();
};
this.getAttribute = function () {
///<summary>Returns the attribute object. Does not chain</summary>
return Xrm.Page.getAttribute(attribute);
};
this.getControl = function () {
///<summary>Returns the attribute object. Does not chain</summary>
return Xrm.Page.getControl(attribute);
};
this.getLabel = function () {
return Xrm.Page.getControl(attribute).getLabel();
};
// Setters
this.setRequired = function (is_Required) {
///<summary>Set the requirement level by Boolean value
/// Sets to none if false or required if true
///</summary>
///<param name="is_Required" type="Boolean">True or false</param>
if (is_Required)
Xrm.Page.getAttribute(attribute).setRequiredLevel($c.requirementLevels.required); // could just use the text value here
else
Xrm.Page.getAttribute(attribute).setRequiredLevel($c.requirementLevels.none);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setRequiredLevel = function (level) {
///<summary>Can use $c.requirementlevel</summary>
///<param name="level" type="BrcXrmConstants.requirementLevels">One of the values 'required', 'recommended', 'none'.</param>
Xrm.Page.getAttribute(attribute).setRequiredLevel(level);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setSubmitMode = function (submitMode) {// always");"never"
///<summary>Can use $c.submitModes. Set form readonly fields to always if changing value in JS code</summary>
///<param name="submitMode" type="BrcXrmConstants.submitModes">One of the values 'always', 'never'</param>
Xrm.Page.getAttribute(attribute).setSubmitMode(submitMode);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setVisible = function (is_visible) {
Xrm.Page.getControl(attribute).setVisible(is_visible);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setDisabled = function (is_disabled) {
Xrm.Page.getControl(attribute).setDisabled(is_disabled);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setDateToday = function () {
///<summary>Sets the given attribute value to the current datetime. This will only work on a datetime attribute</summary>
//if (Xrm.Page.ui.getFormType() == 1) // on create
if (Xrm.Page.getAttribute(attribute).getAttributeType() == $c.attributeTypes.datetime) {
Xrm.Page.getAttribute(attribute).setValue(new Date());
}
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setNotification = function (message) {
///<summary>2013: Sets a notification on an attribute</summary>
Xrm.Page.getControl(attribute).setNotification(message);
return new ShorthandXRM(attribute);
};
this.setFormNotification = function (message, level) {
///<summary>Displays form level notification for this attribute.</summary>
///<param name="message">String: The text of the message </param>
///<param name="level">Type: ERROR, WARNING, INFO</param>
Xrm.Page.ui.setFormNotification(message, level, attribute);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setValue = function (value) {
Xrm.Page.getAttribute(attribute).setValue(value);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setLookupValue = function (id, name, entityType) {
///<summary>Sets a value on a lookup field</summary>
///<param name="id">Guid: The Guid of the record (lowercase with braces?)</param>
///<param name="name">String: The text description value of the record</param>
///<param name="entityType">String: The entity name</param>
var value = [{ id: id, name: name, entityType: entityType }];
Xrm.Page.getAttribute(attribute).setValue(value);
return new ShorthandXRM(attribute); // re-initiate for chaining
};
this.setFocus = function () {
Xrm.Page.getControl(attribute).setFocus();
return new ShorthandXRM(attribute);
};
this.setLabel = function (label) {
Xrm.Page.getControl(attribute).setLabel(label);
return new ShorthandXRM(attribute);
}
this.setShowTime = function (setShowTime) {
///<summary>2013: Specify whether a date control should show the time portion of the date.</summary>
Xrm.Page.getControl(attribute).setShowTime(setShowTime);
return new ShorthandXRM(attribute);
};
this.setPrecision = function(precision){
Xrm.Page.getAttribute(attribute).setPrecision(precision);
return new ShorthandXRM(attribute);
};
}
var $x = function (attribute) {
return new ShorthandXRM(attribute);
};