Switch statement

Chuck Tomasi
Tera Patron

FWIW, I was looking for info to see if I could use a switch statement in a transform script rather than a bunch of if/else. I found no examples in the forums or wiki so I gave it a try. It worked! Here's my solution to take a single character from our HR database on a pay code (S, H, or E) and populate our own field with words.



switch (source.u_paycode.toString()) {
case 'S': target.u_paycode = "Salaried Exempt"; break;
case 'E': target.u_paycode = "Salaried Non-Exempt"; break;
case 'H': target.u_paycode = "Hourly"; break;
default: target.u_paycode = "Hourly";
}


Switch statements are an elegant solution. These work just as expected in JavaScript.

14 REPLIES 14

john_roberts
Mega Guru

Great solution, thanks for sharing to help the next person who searches.


jonsapyta
Kilo Contributor

Note, if you want to use a script on a reference field, you can't put it in a transform script as far as I know (there's no documentation I've found to indicate how to create a new reference field value this way). Finally put it in a field map with a source field script, and it worked.

ex if u_paycode was a reference field:



answer=""

switch (source.u_paycode.toString()) {
case 'S': answer = "Salaried Exempt"; break;
...
}

The answer is then mapped as the value to the target, even if it's a reference field such as department.


Can you declare variables within a case? I wrote some code and it looked like it would pass right over where the variables were declared.

Here is a small sample of the code I created:


ar taskType = g_form.getValue('short_description');
alert(taskType);
switch (taskType){

// Telephony: Need the MAC Address
case "Please configure Desktop Phone and supply MAC address":
var macAddress = g_form.getValue('variables.mac_address');
if(macAddress == "" ){
g_form.setMandatory('variables.mac_address',true);
alert('Make sure that the MAC address is provided before completing this task');
g_form.setValue('state',oldValue);
}
alert("Telephone Change");
break;
....


When the case is true, all I get is the alert Telephone Change. It seems like it skips the declaration and the if statement. I put an alert between those two and I would just get the Telephone Change.

Any ideas or suggestions?


staceybailey
ServiceNow Employee
ServiceNow Employee

Thank you for this, Chuck!   This just saved me.  


I spent the last hour trying to debug a switch statement.   it was the .toString() I was missing.