Using a Function in a CreateScript

1 minute read time.

I have discussed elsewhere how we can reuse functions across different create scripts either in the same screen or between different screens.

One technique is the use of either a specialised table to hold the script definitions or the use of custom_captions table to hold the definition of functions that need to be reused across the system. This technique makes use of the fact that you can instantiate functions from strings via the new Function constructor in JScript.

e.g. functionName = new Function( [argname1, [... argnameN,]] body );

A problem you may run into, is that a function referenced in the Create script does not reference the properties of the field as it would if you were using the code in the Create Script directly.

For example if you used the following code in the create script of the comp_type field in the companyboxlong screen.

function removeOptions()
{
RemoveLook("customer");
RemoveLook("prospect");
}

removeOptions();

we would get the error

comp_type jscript error: Object expected Line: 4 Char: 0

This occurs because we don't have a way of passing the methods and properties of the field (entryblock)into a function. We therefore need to avoid using field (entryblock) properties and methods in functions used in CreateScripts.

To avoid errors like this we need to use the functions to identify the data that we need.

For example we may want to develop the idea of a function that can be used to remove options from the comp_type field depending on the users team. This could be much more complicated but I have kept it as simple as possible.

function changeTypeList(team)
{
if (team != 1)
{
return ["customer", "prospect"];
}
else
{
return ["partner", "supplier"];
}
}

var myArray = changeTypeList(CurrentUser.user_primarychannelid);
for (i = 0; i
{
RemoveLookup(myArray[i]);
}

The function is returning an array that contains the options that need to be removed.

To make this function available for use in other screens then it can be stored in the custom_captions table via the translations screens

Caption Code: changeTypeList
Caption Family: customfunction
US Translation: if (team != 1){return ["customer", "prospect"];}else{return ["partner", "supplier"];}

The code in the createscript of the comp_type in the companyboxlong screen can then be changed to

var changeTypeList = new Function("team",CRM.GetTrans("customfunction","changeTypeList"));
var myArray = changeTypeList(CurrentUser.user_primarychannelid);
for (i = 0; i
{
RemoveLookup(myArray[i]);
}

Note: You should also see the article "Working with Selection Lists".