Interested in a ServiceNow event built for developers? Registration for now[dev]26 is officially open!

Inserting javascript into a field via code without executing the code

Jonas27
Kilo Guru

I want to create a Catalog Item variable via code and in the "default_value" field, there should be the following code:

Jonas27_0-1741099962865.png

 

 


But when I create the Catalog Item variable by code in a UI Policy like this:

 

Jonas27_1-1741100013552.png

 then the "default_value" does not contain

Jonas27_2-1741100039938.png

 

and instead it contains the sys_id of the logged in user.

So is there a way to insert javascript code into the default_value field via code without the code being executed?
10 REPLIES 10

Ankur Bawiskar
Tera Patron

@Jonas27 

but why to create variable via script?

try this and it should give you logged in user if it's a reference variable to sys_user

Also no other way other than script if you are using script. please create variables manually

var variable = new GlideRecord('item_option_new');
variable.setValue('default_value', "javascript: gs.getUserID()");
variable.insert();

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 10x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

@Jonas27 

Thank you for marking my response as helpful.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 10x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Thank you for your suggestion, but I'm still hoping that someone will have a suggestion that helps to solve the problem.

I have to create the variable via script, because it is part of a mechanism for something else. 

@Jonas27 

so with the script I shared did it not set the default value with this javascript: gs.getUserID()

Did you verify by logging in to that form and see if that variable got auto populated with the logged in user in Reference field/variable?

what didn't work for you?

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 10x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

The result of your script is, that in the variable field "default_value" there will be the sys id of the logged in user. So the default value will be hard coded to this sys id.

But in the variable field "default_value" there should not be a hard coded sys id, but this script 

Jonas27_0-1741172808485.png

 

 so that it dynamically looks for the currently logged in user.