Client Scripts

 

Replace String within a String or find something within a String

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
alert (p.replace('dog', 'monkey')) ; <- This is not working in a UI Action

Use:
if (mainString.includes(searchString)) { }


indexOf
https://www.w3schools.com/jsref/jsref_indexof.asp

const str = 'Mozilla';
console.log(str.substring(1, 3));
// Expected output: "oz"
console.log(str.substring(2));
// Expected output: "zilla"

Lovely Dates in Client scripts

GlideDateTime is only for the Server so heres a client script to populate with todays date and time..
This helps:

--> Script 1
function onLoad() {
    // This code will set the field end_date style to Orange if the task is due to finish within 7 days
    // It will set to red if it finished more than 7 days ago
// However if there is an existing "Style" on the field, that will override!
    var todaydt = new Date();

    var endDate = g_form.getValue('end_date');
    var enddte = new Date(getDateFromFormat(endDate, g_user_date_time_format));
    enddte.setDate(enddte.getDate() - 7);

    var dif = enddte - todaydt;
    var control = g_form.getControl('end_date');
    if (dif <= -1190000000) {
        control.style.backgroundColor = "#FF7D61"// a soft red
    } else if (dif >= -1190000000 && dif <= 0) { // This is about 7 days
        // control.style.color = 'blue'; // to set the color of the text in the field but not
        control.style.backgroundColor = "orange";
    } else {
        control.style.backgroundColor = "white";
    }
}


--> Script 2
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

   // The Format must be ---> 01.01.2021 06:00:00
    var d = new Date();
    var year = d.getFullYear(); 
    var month = '' + (d.getMonth() + 1); 
    if (month.length < 2) { month = '0' + month; } 
    var day = '' + d.getDate();
    if (day.length < 2) { day = '0' + day; } 
    
    var hrs= '' + d.getHours();
    if (hrs.length < 2) { hrs = '0' + hrs; } 
    var mins= '' + d.getMinutes();
    if (mins.length < 2) { mins = '0' + mins; } 
    var secs = "00";

    var currTime = day +"." + month + "." + year + " " + hrs + ":" + mins + ":" + secs; //  06:00:00" ;

    if (newValue != oldValue) { // Only update if the value changes
       g_form.setValue("u_etc_effort_update", currTime);
       g_form.save();
    }
}


--> Script 3
// How to compare todays date with another date
var todaydt = new Date(new Date());

var endDate = g_form.getValue('end_date');
var enddte = new Date(getDateFromFormat(endDate, g_user_date_time_format));

//alert(":" + enddte + "  " + todaydt);
if(todaydt < enddte){
     alert("today is earlier than the Planned Date");
else {
     alert("today is later than the Planned Date");
}

Example AJAX call

Option 1:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    // Populate the fiscal dates according to the dates in the Project Task or Project
    if (newValue) {
        var ga = new GlideAjax('BiHaBackFillProjectAJAX');
        ga.addParam('sysparm_name', 'getPrjFiscalDates');
        ga.addParam('sysparm_prsysid', newValue);
        ga.getXML(setFiscalPeriods);
    }

    function setFiscalPeriods(response) {
        var answer = response.responseXML.getElementsByTagName("answer");
        if (answer) {
            g_form.setValue('start_fiscal_period', answer[0].getAttribute("stdte"));
            g_form.setValue('end_fiscal_period', answer[0].getAttribute("endte"));
        }
    }
}

-------- Server Script

    getPrjFiscalDates: function() { 
        var ptSysId = this.getParameter("sysparm_prsysid"); // can be Project or Project Task
        var result = this.newItem('answer');
        var gr = new GlideRecord('planned_task');
        gr.addQuery("sys_id", ptSysId);
        gr.query();
        if (gr.next()) {
var sdt = gr.start_date;
var edt = gr.end_date;
var ex = new ExpenseLinesUtil();
         var stf = ex.calculateFiscalPeriodfromDate(sdt.slice(0, 10));
                var etf = ex.calculateFiscalPeriodfromDate(edt.slice(0, 10));
                result.setAttribute('stdte', stf);
                result.setAttribute('endte', etf);
        }
    },

Option 2:

function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || newValue === '') { return; } var userSelected = g_form.getValue('u_user'); var userDetails = new GlideAjax('UserDetailsUtil'); //script include UserDetailsUtil userDetails.addParam('sysparm_name', 'getUserDetails'); //calling function getUserDetails userDetails.addParam('sysparm_userSelect', userSelected); //passing the user detail as a parameter userDetails.getXMLAnswer(function(response){ var userObj = JSON.parse(response); //parsing the user object received frm getUserDetails fn g_form.setValue('u_contact_no', userObj.contactNo); //setting the value in necessary fields g_form.setValue('u_user_id', userObj.userId); }); }

Option 3: getReference - very nice

GlideForm | ServiceNow Developers

Types of alert

var answer=confirm("are you sure you want to close the attached incident?");
if (answer==true){
}

g_form

var action = g_form.getActionName();  <- to know which UI action has been pressed. Very handy!
    if (action == 'sysverb_cancel') {.  <-this is the aciton name
g_form.addInfoMessage("You must delete Breakdowns first1111"); 
g_form.addErrorMessage("You must delete Breakdowns first1111"); 
g_form.addErrorMessage(getMessage("benefitplandelete"));

Use "getMessage("benefitplandelete")" to get stuff from the Messages table

In a Client Script - Using g_form.getReference

This is a great way of getting a value on a record in a Reference field 
I used this on a change of the field u_created_from. It gets the whole record of u_dmn_estimation and in the callback. However you cant dot walk beyond the record
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    // Update Field "demand"
    var crtfr = g_form.getReference('u_created_from', userLookup);
    
function userLookup(crtfr) {
g_form.setValue('demand', crtfr.parent);
    }
}

g_scratchpad

passes information from the server to the client, such as when the client requires information not available on the form
But you can use this to pass values between client scripts:
    g_scratchpad.testGlobalVar = "butCreatedFrom";

User Object cheat sheet

https://servicenowguru.com/scripting/user-object-cheat-sheet/

Get the users current language:
var userLanguage = g_lang;


Reference Field

Can I have a different display value in a Reference field to the one defined in the dictionary?
So in any table there can only be one display value. 
But suppose I want to show another field ? e..g planned task - the display value is the number. But suppose instead of the number, I want to display the WBS?

STILL TODO


UI Action to go to a link

Make sure that client checkbox is selected (if not it means the code runs on the server)
function showBPCrechnung() {
        var sapid = g_form.getValue("u_sap_id");
var url = g_scratchpad.sapProperties.SAPBaseURLhttps; 
url = url + "/bc/archiveLink?SAP-ID=" + sapid;
url = url + "&sap-client=510&sap-language=DE";
g_navigation.open(url, '_blank');
}

If client checkbox is not selected it means its running on the server. 
This means use:
  action.setRedirectURL(current);

Stop a catalog item from submitting based on a field value

onChangeCode
// I added a hidden field called u_hidden_value
function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    // 1. newValue is from the sys_user_grmember table
    // 2. Check if the User has a date and Group in the sys_user "u_expirytime" & "u_expiry_remote_group" fields
    // 3. If they do then it means they have permissions already
    // 4. If they have permissions, inform them and stop the submittion
    //var inputValue = g_form.getValue(controlName);
    if (newValue) {
        var ga = new GlideAjax('UserDataUtils');
        ga.addParam('sysparm_name', 'doesUseralreadyHaveApptunnelReq');
        ga.addParam('sysparm_sysid', newValue);
        ga.getXML(userExistingAccess);
    }

    function userExistingAccess(response) {
        var answer = response.responseXML.getElementsByTagName("answer");
        if (answer) {
            var ans = answer[0].getAttribute("HASACCESS");
            if (ans == "YES") {
                g_form.setValue('u_hidden_value', answer[0].getAttribute("exttime"));
                g_form.showFieldMsg("u_supplier_user", "This User already has access until - " + answer[0].getAttribute("exttime"), 'error');
            } else {
                g_form.setValue('u_hidden_value', "");
            }
        }
    }
}

onLoad Code
function onSubmit() {
    var exval = g_form.getValue("u_hidden_value");
    if (exval) {
        g_form.showFieldMsg("u_supplier_user", "This User already has access until - " + exval, 'error');
        return false;
    }
}


OnChange catalog client script calling a function in onLoad



onLoad Code
// You need to disable "Isolate script" on your onLoad script 
function onLoad() {
    //Type appropriate comment here, and begin script below
}

checkPrimaryRole = function () { // You must have this format for the function to work!
	alert('in the function');
}

onChangeCode
function onChange(control, oldValue, newValue, isLoading) {
	
    if (isLoading || newValue == '') {
        return;
    }
	
	checkPrimaryRole();
}

Comments

Popular posts from this blog

Email Templates and Emails

Arrays

ServiceNow tips