If you ever need to pass an Array as parameter inside the Event Handler form, you can declare it with the square brackets or using the Array keyword:
// square brackets [1, 2, 3, 4 ,5] // Array keyword new Array(1, 2, 3, 4, 5)CRM Event Handler:
As example we write a function to hide fields passing their logicalname as an array:
["name", "accountnumber", "telephone1"]the function handles the parameter in this way:
function HideFields(fields) { for (var count = 0; count < fields.length; count++) { if (Xrm.Page.getControl(fields[count]) != null) { Xrm.Page.getControl(fields[count]).setVisible(false); } } }If a parameter is an Array, multiple parameters can still be passed inside the Event Handler. For example:
// note the comma before the array is declared true, ["name", "accountnumber", "telephone1"]In this way we are sending a boolean as first parameter to our updated function:
function ShowHideFields(isVisible, fields) { for (var count = 0; count < fields.length; count++) { if (Xrm.Page.getControl(fields[count]) != null) { Xrm.Page.getControl(fields[count]).setVisible(isVisible); } } }There is another way to pass multiple parameters without declaring each parameter inside the function definition and without using an Array: the arguments variable.
In JavaScript the arguments variable holds automatically all the parameters passed to a function.
We can rewrite the previous example, inside the Event Handler we pass the values as separate parameters, not as an array:
// no square brackets, no Array Keywords, just 3 separate parameters "name", "accountnumber", "telephone1"and our function is simply this one:
function HideFields() { for (var count = 0; count < arguments.length; count++) { if (Xrm.Page.getControl(arguments[count]) != null) { Xrm.Page.getControl(arguments[count]).setVisible(false); } } }But if we want to handle a specific element (like the first element) we need to take care inside the code:
// we decided that the first parameter will contain the value for the isVisible variable true, "name", "accountnumber", "telephone1"
function ShowHideFields() { // this function requires at least 2 parameters if (arguments.length > 1) { var isVisible = arguments[0]; // we start the for cycle from 1 instead of 0 for (var count = 1; count < arguments.length; count++) { if (Xrm.Page.getControl(arguments[count]) != null) { Xrm.Page.getControl(arguments[count]).setVisible(isVisible); } } } }
Rather than use javascript arguments, I would prefer to pass a single JSON parameter. I find this much easier to understand as it almost self-documents
ReplyDelete{
isVisible: true,
fields: ["name", "accountnumber", "telephone1"]
}
function ShowHideFields(settings) {
if (settings) {
for (var count = 0; count < settings.fields.length; count++) {
if (Xrm.Page.getControl(settings.fields[count]) != null) {
Xrm.Page.getControl(settings.fields[count]).setVisible(settings.isVisible);
}
}
}
}