
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
NOTE: MY POSTINGS REFLECT MY OWN VIEWS AND DO NOT NECESSARILY REPRESENT THE VIEWS OF MY EMPLOYER, ACCENTURE.
DIFFICULTY LEVEL: BEGINNER
Assumes good intermediate level knowledge and/or familiarity of Scripting in ServiceNow.
I see this particular coding technique from time-to-time. Use of the eval(...) statement to be able to dynamically get and/or set a GlideRecord record field.
var incidentRecords = new GlideRecord('incident');
incidentRecords.setLimit(5); // keep this small for testing
incidentRecords.query();
while (incidentRecords.next()) {
var incidentField = 'incidentRecords.impact';
var incidentFieldValue = eval(incidentField).getDisplayValue(); // don't do this please.
gs.info('---> Impact:' + incidentFieldValue);
}
Gave me the following result:
The value could be accessed without using eval by using the array bracket notation:
var incidentRecords = new GlideRecord('incident');
incidentRecords.setLimit(5); // keep this small for testing
incidentRecords.query();
while (incidentRecords.next()) {
var incidentField = 'impact';
var incidentFieldValue = incidentRecords[incidentField].getDisplayValue(); // this is a best practice
gs.info('---> Impact:' + incidentFieldValue);
}
Gave the same result!
Okay, so here is a use case example:
var tableName = 'incident';
var fieldName = 'impact';
var fieldValue = 1;
var checkName = 'number';
var checkValue = 'INC0010023';
setFieldValue(tableName, fieldName, fieldValue, checkName, checkValue);
function setFieldValue(table, field, value, check, checkValue) {
var genericTable = new GlideRecord(table);
genericTable.addQuery(check, checkValue);
genericTable.query();
while (genericTable.next()) {
genericTable[field] = fieldValue + '';
// genericTable.update(); // this is part of what would really be here in real code. really.
gs.info('--->\n\ttable: {0}\n\tfield: {1}\n\tfield value: {2}',
[table, field, genericTable[field]]);
}
}
Gives the following result:
As you can see, you could really get wild with this if you had some sort of driver table, that you pulled the information from, that you wanted to pass to the setFieldValue function.
If you want to know more about why eval should be avoided read in the book 'Javascript: The Good Parts' by Douglas Crockford (link). The big one is: "It compromises the security of your application because it grants too much authority to the eval'd text." p.111.
Remember: eval is evil! 🙂
Enjoy!
Steven Bell.
If you find this article helps you, don't forget to log in and mark it as "Helpful"!
Originally published on: 08-25-2015 11:58 AM
I updated the code and brought the article into alignment with my new formatting standard.
- 1,340 Views
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.