Search code examples
javascriptservicenow

Possible to use placeholders in sys_properties?


Is it possible to create a sys_property value such as:

This incident has been picked up by {person_name} for further investigation

And then in the code use something like:

var assignee = "John Doe";
var prop = gs.getProperty('my_property_name');    
// and now replace person_name with the value of assignee variable?

Solution

  • You can use the RecordToHTML API, traditionally it's used for using the fields from a record as the replacement values for the string fields, however, with the help of .setValue(), you can bypass the record arguments and specify your own values. Note for this to work your "variables" in your string need to be wrapped in ${} and not {}:

    var prop = gs.getProperty('my_property_name'); // "This incident has been picked up by ${person_name} for further investigation";
    var assignee = "John Doe";
     
    var rth = new RecordToHTML(null, null, prop);
    rth.setValue("person_name", assignee); // replaces ${person_name} with "John Doe"
    
    var result = rth.toString(); // "This incident has been picked up by John Doe for further investigation"
    

    The above is a little hacky, as it bypasses the record arguments. If you want to go for another appraoch you can create your own function for this. You can firstly put assignee into an object that holds the key person_name and points to your assignee value, then use a function to replace values within {<key>} using the key as the key to index your object:

    function interpolate(str, obj) {
      return str.replace(/{([^}]+)}/g, function(match, key) {
        return obj[key] || match; // if we can't find the key, return the original `{key}`
      });
    }
    
    var variableMap = {
      "person_name": "John Doe" // assignee
    };
    
    var prop = gs.getProperty('my_property_name');
    var msg = interpolate(prop, variableMap); // "This incident has been picked up by John Doe for further investigation"
    

    There are some other options that you can use that may do what you're after that are also worth looking into. One being using the first arguments of RecordToHTML() and another being gs.getMessage(). RecordToHTML can also be good if you have a particular record that contains the fields you want to replace from your string (note that your fields need to be wrapped in ${}):

    var rth = new RecordToHTML("incident", incidentSysId, "This incident has been picked up by ${assigned_to} for further investigation", false);
    var result = rth.toString();
    

    There is also gs.getMessage(), which comes close, but it doesn't allow for named "variables" within your string and requires you to use indexes. It also performs a table query / lookup in the sys_ui_message table each time it is called which may be overkill:

    // prop = This incident has been picked up by {0} for further investigation
    var msg = gs.getMessage(prop, [assignee]);