The Zurich release has arrived! Interested in new features and functionalities? Click here for more

script to check if a variable exists

Aka Guglielmo
ServiceNow Employee
ServiceNow Employee

Do you have any idea on how to check, inside a workflow, if a variable exists?

Let me say, something like: if (current.variables.variableName.exists).

Because if (current.variables.variableName != '') returns an error.

Thanks

1 ACCEPTED SOLUTION

I suppose an even easier way is just to test it.



if (current.variables.var_name) {


        // The variable exists and is not null


} else {


        // The variable does not exist


}



The same can be done with fields as well to avoid null pointer exceptions. See the best practices.



Reference:


ServiceNow Wiki: Technical Best Practices


View solution in original post

13 REPLIES 13

Hopefully someone can respond to this....

 

@chucktomasi 

 

If a variable exists on the catalog item but I have not added it to appear on the catalog task, how will this effect the above return values in your script?

 

Will it assume the variable doesn't exist if the variable isn't visible on the form? If so, this may be a good way to check if a variable is visible on a form. (I know this doesn't exist but it would be nice is there was a .isVisible function so I can use that in client scripts that require different rules for each task.)

 

 

Hi Chuck,

The ServiceNow Wiki link does not exist, can you please provide the updated link of the wiki?

Chuck Tomasi
Tera Patron

You could write your own that would go through all variables for that record and check if a specific one exists. Here's an untested example associated with the approval field on a sysapproval_approver record...



 


if (varExists('foo')) {


        // Do something


}



function varExists(varName){


      var set = new GlideappVariablePoolQuestionSet();


      set.setRequestID(current.getValue('sysapproval'));


      set.load();


      var vs = set.getFlatQuestions();


      for (var i=0; i < vs.size(); i++) {


              if(vs.get(i).getLabel() == varName) {


                      return true;


              }


      }


      return false;


}


Hi chuck,



WE have a SMVariable editor which we are using in a scoped application. when i try to display this in service portal it gives me an error saying "GlideappVariablePoolQuestionSet is not allowed in scoped applications". Any clue how can we get the variables if this method does not work in scoped app.


I also need to get the containers associated with variable editor in order to maintain   consistency and order.



Eagerly waiting for reply.



Thanks in advance .




Thanks and Regards,


Zabeeulla.


Good question. Let me do some checking.