Get field value of GlideRecord (best practice method)

xiaix
Tera Guru

var gr = new GlideRecord('incident');

gr.addQuery('active', 'true');

gr.query();

if (gr.next())

{

  // This way ?

  gr.sys_id;

  // Or this way ?

  gr.getValue('sys_id');

}

Which is safest/best method to get the value?   Dotwalk the gr object or use the built-in method, getValue() ?

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

I prefer gr.getValue('sys_id');



gr is a pointer. If you pop the sys_ids in to an array, you get a list of all of the same values (of the last record.)   getValue() copies the value rather than using the reference.



getValue() has saved my life more times than I care to admit. While it's not perfect, it's often the better option to ensure you have the value (especially in loops.)



As a general rule, getters/setters are a better way to go in object oriented programming.


View solution in original post

7 REPLIES 7

Agreed, and as I'm sure has been mentioned in other places --

GlideRecord.getUniqueValue() 
should be preferred over

GlideRecord.getValue("sys_id")

 

Katie A
Mega Guru

I also like gr.getValue(); because you can pass in a variable to set the field name, instead of a hard-coded string.

This is helpful when creating generic methods to search by fields dynamically when you do not necessarily know the field you want to search by ahead of time.

Example:

var SearchQueryUtil = Class.create();
SearchQueryUtil.prototype = {
  initialize: function () {},

  getValueByID: function (table, sys_id, field) {
	var result_value = '';
    var gr = new GlideRecord(table);
    gr.addQuery('sys_id', sys_id);
    gr.query();

    if (gr.next()) {
      result_value = gr.getValue(field);
    }

	return result_value;
	
  },

  type: 'SearchQueryUtil'
};

What does field imply in this?