Record view count - Best Approach

gaidem
ServiceNow Employee
ServiceNow Employee

I'm looking to have an integer that shows how many times a record has been viewed. What's the most efficient way of achieving this?

10 REPLIES 10

gaidem
ServiceNow Employee
ServiceNow Employee

So I put this inside a display BR:



current.u_view_count +='1';
current.update();


The result was that the form would not load at all. Am I doing something wrong?


gaidem
ServiceNow Employee
ServiceNow Employee

Here's what I ended up doing:
Business Rule
When: Display
Condition: current.isValidRecord()
Script:



var usr = gs.getUserDisplayName();
var time = gs.nowDateTime();
var incID = current.sys_id;
var incREC = new GlideRecord('incident');
incREC.addQuery('sys_id',incID);
incREC.query();
if(incREC.next()){
incREC.u_view_count+=1;
incREC.u_internal_notes =usr+" viewed this record at "+time;
incREC.update();
}


CapaJC
ServiceNow Employee
ServiceNow Employee

Interesting that you had to get the GlideRecord that way vs. just using current. Maybe something about updating current in a "display" rule is bad.

Anyway, if you're intsrested, you might do the record "get" with fewer lines as follows:

var incREC = new GlideRecord('incident');
if (incREC.get(current.sys_id))
incREC.u_view_count += 1;
incREC.u_internal_notes = gs.getUserDisplayName() + " viewed this record at " + gs.nowDateTime();
incREC.update();
}


gaidem
ServiceNow Employee
ServiceNow Employee

This is very interesting, I've never seen the "get" option anywhere before... Is this on the wiki anywhere? Does this reduce the query time a normal GlideRecord does?

Thanks!


CapaJC
ServiceNow Employee
ServiceNow Employee

I think we have an API page on GlideRecord, but I've not looked in awhile. gr.get(id) is useful if you're going after one record. It also returns a boolean, so you can do the following in a function to get out early if there's no record:

if (!gr.get(id))
return;

And it's PROBABLY doing less work than using addQuery, query, next - though unless you're talking about something happening millions of times a day, I doubt the difference is of any significance.