Business Rule: gr.next returns false but works fine in 'Scripts Background'

andy_dufresne
Tera Expert

Hello Gurus,

There is no other business rule that is interfering with it.

When I debugged it the gr.next() was returning false

(function executeRule(current, previous /*null when async*/) {

id=current.sys_id;

var gr = new GlideRecord('contact');

//var eq = 'document='+ id +'^type=sys_user';

var eq = "type=sys_user^document="+ id;

gr.addEncodedQuery(eq);

gr.query();

while (gr.next()){

current.u_mojusersemailaddressholder += gr.user.email +',';

//gs.print(gr.user.email);

}

})(current, previous);

If I run in scripts background, gr.next is true.

What am I doring wrong?

Thanks,

12 REPLIES 12

Thanks for the excellent debug info Andy.   What happens if we request the encoded query from each?



(function executeRule(current, previous /*null when async*/) {  


 


var id=current.getValue('sys_id');  


      var gr = new GlideRecord('contact');  


      //var eq = 'document='+ id +'^type=sys_user';  


      gr.addQuery('document', id);  


      gr.addQuery('type', 'sys_user');  


      gr.query();  


 


gs.log('getRowCount is : ' + gr.getRowCount());  


gs.log('the id value is:' + id);  


gs.log('the query is :' + gr.getEncodedQuery());  


 


 


while (gr.next()){  


current.u_mojusersemailaddressholder += gr.user.email +',';  


}  


 


//}  


 


})(current, previous);


Gentlemen,



Firstly BIG thanks for jumping in straight away.   This solved the problem:



  1. I changed the Business Rule from 'before insert' to 'after insert'
  2. then I added the current.update();

(function executeRule(current, previous /*null when async*/) {


  id=current.sys_id;



var gr = new GlideRecord('contact');


var eq = 'document='+ id +'^type=sys_user';


gr.addEncodedQuery(eq);


gr.query();



              if (current.u_mojusersemailaddressholder == ''){


while (gr.next()){


current.u_mojusersemailaddressholder += gr.user.email +',';


}


current.update();



}



})(current, previous);


Hi Andy... you really don't want to do an AFTER business rule when updating the current record. Adding the current.update() triggers business rules again! Bad practice.



I didn't realize you were doing this on INSERT, that makes sense because you don't have a sys_id until the save is done. That being said, there are a couple more things to try.



First, instead of



var id = current.getValue('sys_id');



try this (in a before/insert rule please)



var id = current.getUniqueValue();



Failing that, change it back to an after/insert rule and PLEASE add this before your current.update();



current.setWorkflow(false); // do not trigger additional BRs



Reference:



Business Rules Best Practices - ServiceNow Wiki  


Hi Chuck,



I tried that and it gives me this:


find_real_file.png


You tried which?