Pulling Variables to Email Notification

Sofija
Giga Expert

Hi All,

I have an email script that pulls variables in an organized manner to an approval email notification. However, it only pulls them if in catalogue item I used a variables set rather than individual variables. For example, if my service catalog item has a variables set of 10 items, email script will pull all of them. However, if I have a catalogue item with 10 variables, it will pull just a few of them. Could anyone be able to help me with this so all variables are pulled no matter if there is a variable set or not?

Here is the email script:

var reqI = new GlideRecord("sc_req_item");
reqI.addQuery("sys_id", current.sysapproval);
reqI.query();
if(reqI.next()) {
new Var2Desc().printVariables(reqI,function(){}, true);

}

Here is script include:

var Var2Desc = Class.create();
Var2Desc.prototype = {
      initialize: function() {
  /* map: element vs internal field type */
this.UI_PAGE = 15,
this.MASKED = 25,
this.DATE = 9,
this.NUMERIC_SCALE = 4,
this.CHECKBOX = 7,
this.MULTIPLE_CHOICE = 3,
this.DATE_TIME = 10,
this.CONTAINER_END = 20,
this.LABEL = 11,
this.WIDE_SINGLE_LINE_TEXT = 16,
this.YES_NO = 1,
this.HTML = 23,
this.SELECT_BOX = 5,
this.MACRO = 14,
this.REFERENCE = 8,
this.LOOKUP_MULTIPLE_CHOICE = 22,
this.LIST_COLLECTOR = 21,
this.MULTI_LINE_TEXT = 2,
this.SINGLE_LINE_TEXT = 6,
this.MACRO_WITH_LABEL = 17,
this.LOOKUP_SELECT_BOX = 18,
this.SPLIT = 24,
/* this is a list of elements that will be ignored */
this.IGNORE = [this.UI_PAGE, this.CONTAINER_END, this.HTML, this.MACRO,
this.MACRO_WITH_LABEL, this.SPLIT, this.LABEL];

      },

/*
* ritm           GlideRecord object
* func           javascript function to customize conditions
*                     to skip centain variables values
* noBlanks   true|false to avoid empty variable's value
*/
printVariables: function(ritm, func, noBlanks) {
gs.print("here in script");
var d = '';
var noBlanks = noBlanks || false;
var vars = this._getVariablesSorted(ritm);

/* loop the variables */
for(var i =0; i < vars.length; i++) {
var o = vars[i];
var type = o.type;
var label = o.label;
/* ignore list of types */
if(this._isIgnored(o.type))
continue;

/* if custom function is provided, execute custom conditions */
if(func && typeof func == 'function') {
if(func.call(this,o)) continue;
}

  var v = o.value;
if(gs.nil(v)) {
if(noBlanks)
continue;
} else {
/* for reference fields get the Display Value */
if(type == this.REFERENCE || type == this.LIST_COLLECTOR) {
v = v.getDisplayValue();
} else if(type == this.MULTI_LINE_TEXT) {
/* for multi line place an extra line in front
and ident every line with one space */
v = "\n " + o.value.toString().replace(/\n/g,"\n ");
}   else if(type == this.MULTIPLE_CHOICE || type == this.SELECT_BOX) {
/* get choices */
var choices = question.getChoiceList();
/* get label of value selected */
v = choices.getLabelOf(v);
}
}

template.print("<br>"+label+"</br>");
template.print("<br>"+v+"</br>");
}

},

_getVariablesSorted: function(ritm) {
var vars = [];
for(var variableName in ritm.variables) {
/* GlideObject */
var go = ritm.variables[variableName].getGlideObject();
/* Question */
var question = go.getQuestion();
/* Label */
var label = go.getQuestion().getLabel();
/* Type (numeric value) */
var type = new Number(go.getType());
/* Order (numeric value) */
var order = new Number(go.getQuestion().getOrder());
/* creates an Object */
var o = {
'name': variableName,
'label': label,
'value': ritm.variables[variableName],
'order': order,
'type': type
};
vars.push(o);
}
/* return the variables in order as per the form */
return this._quicksort(vars);
},

/* quick sort algorithm */
_quicksort: function(arr) {
if (arr.length === 0) {
return [];
}
var left = [];
var right = [];
var pivot = arr[0];
for (var i = 1; i < arr.length; i++) {
/* compare order from object */
if (arr[i].order < pivot.order) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return this._quicksort(left).concat(pivot, this._quicksort(right));
},

/* check if the given field type should be ignored */
_isIgnored: function(type) {
for(i=0; i < this.IGNORE.length; i++)
if( this.IGNORE[i] == type)
return true;
return false;
},


      type: 'Var2Desc'
}


Kind Regards,

Kamile

1 ACCEPTED SOLUTION

Sofija
Giga Expert

For those still looking for solution to this here email script that does the work beautifully:



// Get Requested Item


var reqitem = new GlideRecord('sc_req_item');


reqitem.addQuery("sys_id", current.sysapproval);


reqitem.query();


while(reqitem.next()) {


// Get Owned Variables for Requested Item and sort by Order


var ownvar = new GlideRecord('sc_item_option_mtom');


ownvar.addQuery('request_item.number', reqitem.number);


ownvar.addQuery('sc_item_option.value','!=','');


ownvar.orderBy('sc_item_option.order');


ownvar.query();


while(ownvar.next()) {


  // Add Question, Answer and Order into notification mail


  // Set variable v to variable name


  var field = ownvar.sc_item_option.item_option_new;


  var fieldValue = ownvar.sc_item_option.item_option_new.name;


 


  // Print variable name


  template.print( '<b>' + field.getDisplayValue() + '</b>' + '\n');


 


  // Print Display Value for each variable in Requested Item


  template.print( reqitem.variables[fieldValue].getDisplayValue() + "\n\n");


 


}


}


View solution in original post

51 REPLIES 51

There are more than few types of code that are there on community that pulls the variable information. Any specific needs why yours seems different ?   Does it try to replicate the variable UI on the email?


Mine organizes items in the manner that they appear on the request form. This is the goal that I am trying to achieve with this code. I had one that used to pull all variables, however, it would pull them in a random manner. Now I have this one that pulls them in organized manner but only works for variable sets, and for variables it's missing data. Any thoughts?


Hi Kalai,


This is all in one utility script which was found while looking over community and site.


It does following things



1) Pull all the variables in order


2) Can ignore blank variables


3) Can ignore selected varaibles as well.


var gr = new GlideRecord("sc_req_item");


gr.addQuery("request", current.sys_id);


gr.query();


while(gr.next())


{


var stage = gr.stage.getDisplayValue();


if (JSUtil.nil(stage))


stage = gr.stage.getChoiceValue();


template.print("<p id='LabelVar'><b>Requested item Details:</b></p>\n");


template.print('Number: ' + gr.number +'\n' + 'Name: '+ gr.cat_item.getDisplayValue() + '\n'+ "Stage: " + stage + "\n"+ '<div>  </div>');


var v2d = new Var2Notification();


template.print('\n' + ' ' + v2d.getDescription(gr, function(obj) {


  /* skip 'myothervariable' value */


  return (gr.variables.v_imac_un != '' &&


      obj.name == 'v_imac_un') ||(gr.variables.v_approval != '' &&


      obj.name == 'v_approval');


},true));


}



Email Script which will call the script include.



var Var2Notification = Class.create();


Var2Notification.prototype = {


initialize: function() {


  /* map: element vs internal field type */


  this.UI_PAGE = 15,


  this.MASKED = 25,


  this.DATE = 9,


  this.NUMERIC_SCALE = 4,


  this.CHECKBOX = 7,


  this.MULTIPLE_CHOICE = 3,


  this.DATE_TIME = 10,


  this.CONTAINER_END = 20,


  this.LABEL = 11,


  this.WIDE_SINGLE_LINE_TEXT = 16,


  this.YES_NO = 1,


  this.HTML = 23,


  this.SELECT_BOX = 5,


  this.MACRO = 14,


  this.REFERENCE = 8,


  this.LOOKUP_MULTIPLE_CHOICE = 22,


  this.LIST_COLLECTOR = 21,


  this.MULTI_LINE_TEXT = 2,


  this.SINGLE_LINE_TEXT = 6,


  this.MACRO_WITH_LABEL = 17,


  this.LOOKUP_SELECT_BOX = 18,


  this.SPLIT = 24,


  /* this is a list of elements that will be ignored */


  this.IGNORE = [this.UI_PAGE, this.CONTAINER_END, this.HTML, this.MACRO,


      this.MACRO_WITH_LABEL, this.SPLIT, this.LABEL];


},



/*


  * ritm           GlideRecord object


  * func           javascript function to customize conditions


  *                     to skip centain variables values


  * noBlanks   true|false to avoid empty variable's value


  */


getDescription: function(ritm, func, noBlanks) {


  var d = '';


  var noBlanks = noBlanks || false;


  var vars = this._getVariablesSorted(ritm);


 


  /* loop the variables */


  for(var i =0; i < vars.length; i++) {


    var o = vars[i];


    var type = o.type;


    var label = o.label;


    /* ignore list of types */


    if(this._isIgnored(o.type))


      continue;


   


    /* if custom function is provided, execute custom conditions */


    if(func && typeof func == 'function') {


      if(func.call(this,o)) continue;


      }


   


    var v = o.value;


    if(gs.nil(v)) {


      if(noBlanks)


        continue;


    } else {


      /* for reference fields get the Display Value */


      if(type == this.REFERENCE || type == this.LIST_COLLECTOR) {


        v = v.getDisplayValue();


      } else if(type == this.MULTI_LINE_TEXT) {


        /* for multi line place an extra line in front


        and ident every line with one space */


        v = "\n " + o.value.toString().replace(/\n/g,"\n ");


      }   else if(type == this.MULTIPLE_CHOICE || type == this.SELECT_BOX) {


        /* get choices */


        //var choices = question.getChoiceList();


        /* get label of value selected */


        v = v.getDisplayValue();


      }


    }


    /* insert a new line for every variable/value pair */


    if(d.length>0)


      d+="\n";


    /* set the label of the variable with it's corresponding value */


    d = d+ '<div><div id="LabelVar"> ' +'<b>'+label+'</b>'+": "+'</div>'+'</div>'+v +'' +'\n';


  }


  return d;


},



_getVariablesSorted: function(ritm) {


  var vars = [];


  for(var variableName in ritm.variables) {


    /* GlideObject */


    var go = ritm.variables[variableName].getGlideObject();


    /* Question */


    var question = go.getQuestion();


    /* Label */


    var label = go.getQuestion().getLabel();


    /* Type (numeric value) */


    var type = new Number(go.getType());


    /* Order (numeric value) */


    var order = new Number(go.getQuestion().getOrder());


    /* creates an Object */


    var o = {


      'name': variableName,


      'label': label,


      'value': ritm.variables[variableName],


      'order': order,


      'type': type


    };


    vars.push(o);


  }


  /* return the variables in order as per the form */


  return this._quicksort(vars);


},



/* quick sort algorithm */


_quicksort: function(arr) {


  if (arr.length === 0) {


    return [];


  }


  var left = [];


  var right = [];


  var pivot = arr[0];


  for (var i = 1; i < arr.length; i++) {


    /* compare order from object */


    if (arr[i].order < pivot.order) {


      left.push(arr[i]);


    } else {


      right.push(arr[i]);


    }


  }


  return this._quicksort(left).concat(pivot, this._quicksort(right));


},



/* check if the given field type should be ignored */


_isIgnored: function(type) {


  for(i=0; i < this.IGNORE.length; i++)


    if( this.IGNORE[i] == type)


    return true;


  return false;


},



type: 'Var2Notification'


};



Script Include which I am using.



What version of ServiceNow are you on.