Set g_form value not working

prernabhandari
ServiceNow Employee
ServiceNow Employee

Hello All,

I ran into something very strange/interesting today. I created a new field "xyz" on my table and then in my client script

I wrote g_form.setValue('xyz',value). Thus setting the value to the field. However when I tried to console.log it xyz didn't   hold any value.

Strange thing   happened   when I put this field on the form layout , I could assign it a value.

Anybody ran into something like this? Any ideas.

I dont want that field to be present in the form layout and I don't see the need to put it there on the layout and then create a UI policy to hide it.

TIA

Prerna

1 ACCEPTED SOLUTION

cameronrichard
ServiceNow Employee
ServiceNow Employee

Hi Prerna,



You will need to have the field on the form for your script to work.



You can test the difference...with field xyz on the form type this into your javascript console:


        console.log(g_form.getControl("xyz"));



You see it output the HTML element for your field. Try it again after removing the field and you'll get undefined.



g_form.setValue uses getControl when it's trying to set the value of a field. If it can't find the field to set it returns without doing anything.



You've already stated the solution in your question, you need to add the field to the form and hide it with a UI Policy.



Thanks,



Cameron


View solution in original post

4 REPLIES 4

cameronrichard
ServiceNow Employee
ServiceNow Employee

Hi Prerna,



You will need to have the field on the form for your script to work.



You can test the difference...with field xyz on the form type this into your javascript console:


        console.log(g_form.getControl("xyz"));



You see it output the HTML element for your field. Try it again after removing the field and you'll get undefined.



g_form.setValue uses getControl when it's trying to set the value of a field. If it can't find the field to set it returns without doing anything.



You've already stated the solution in your question, you need to add the field to the form and hide it with a UI Policy.



Thanks,



Cameron


Ajai S Nair
Giga Guru

Hi Prerna,



What Cameron has told is correct. g_form in the client script will work on the fields visible on the form. It is referring directly to the variables on the current form which we have written the client script on. But if you want to assign a value to a variable without showing it on the form then you can try by written a business rule on that table. Else you have to make the form visible and hide it with Ui policy just like what cameron already suggested.


Govind Kumar S1
Kilo Guru

Hi Prerna,



Is your Query Answered?? Please let us know



Thanks & Regards


Govind Kumar Sharma


prernabhandari
ServiceNow Employee
ServiceNow Employee

Thanks for the help!