logo

NJP

Set variables to read-only on a form

Import · May 26, 2019 · article

If you're using a variable set formatter and need to set all the variables to read only and/or hide blank values, try this in a client script

Warning: Here be jQuery dragons...

function onLoad() {

    //get the window object
    var win = (0,eval)('this');

    console.log('%c-----------------------------------------------','color:red'); 
    console.log('%cVariables should be read only & hidden if empty','color:red');
    console.log('%c-----------------------------------------------','color:red'); 

    //Is this user part of a group that can edit variables after the fact?
    var hasRole = g_user.hasRoleExactly('u_sap_user') || g_user.hasRoleExactly('u_hr_user');  

    //Loop through variables
    win.jQuery('[id^="ni.QS"][type!="HIDDEN"]').each(
        function(index, thisVar){
            //Hide if there's no value
            if(g_form.getValue('variables.'+thisVar.name)==''){
                g_form.setDisplay('variables.'+thisVar.name,false);
            }
            //Set to read only if not an exempt user
            if(!hasRole){
                g_form.setReadOnly('variables.'+thisVar.name,true); 
            }
        }
    );

    //Look for multi-row variable sets
    win.jQuery('.sc-multi-row-actions').css('visibility','hidden');
    win.jQuery('.sc-table-variable-buttons').css('visibility','hidden');

    //You'll need to name slushbuckets individually 
    win.jQuery('span[name="thisVarName"]').find('div.row').find('div.m2m_filter_container').css( 'visibility','hidden');
    win.jQuery('span[name="thisVarName"]').find('div.row').find('div.form-group').css( 'visibility','hidden');
    win.jQuery('div.slushbucket-top').find('select').attr('disabled',true);

}
View original source

https://www.servicenow.com/community/now-platform-articles/set-variables-to-read-only-on-a-form/ta-p/2310814