Reverse actions of onLoad client script and run function UI Action

Eheitman
Tera Guru

Goal: Click a UI action that sets the Variable Editor read only = false and then runs code to translate the fields

 

Our business has the variable formatter read only by default, disabling the onLoad client script is not an option

 

I have both pieces working independently but I cannot get them to run together in one UI Action

My first function varReadOnlyFalse() will set the field read only but only after the translateVariables() function runs and errors. I attempted to run a current.insert before calling translateVariables() but that will just end the script. If I remove varReadOnlyFalse() and just run translateVariables() with the onLoad client script disabled it will run as expected

 

Is there another way I can trigger varReadOnlyFalse() then translateVariables() in that order? 

 

 

 

function varReadOnlyFalse() {

	$("variable_map").querySelectorAll("item").forEach(function(item){
	var variable = item.getAttribute("qname"); 
	g_form.setReadOnly("variables."+ variable, false);
	variTranslate();
});
}

function variTranslate(){
	// decorate the appropriate variables
        var getVars = g_sc_form.elements;
		alert(getVars);
		var loop = '';
        var varJSON = JSON.stringify(getVars);
		alert(varJSON);
        // now we need to find the variables we care about
        var varName = '';
        var getVarStr = JSON.parse(varJSON, function(key, value) {
 

            if (value.toString().includes('ni.')) {
                varName = value.toString();
				alert(varName);
            }
             if (key == 'type' && value == 'string' && varName != '') {
                 // we need to parse the field label of the variable
                 g_sc_form.addDecoration(varName, "icon-global");
             }
			alert("20");

		
        });
		
		translateVariables();
		
	}
	variTranslate();

	function translateVariables(){

try {

		//alert("22");
        // now we need to get the text for translation
        var theVars = g_sc_form.getEditableFields();
		//alert(theVars);
        var theVarsArr = theVars.toString().split(',');
		//alert(theVarsArr);
        for (var v1 = 0; v1 < theVarsArr.length; v1++) {
            var varVal = theVarsArr[v1].toString();
			alert(varVal);
            var varValue = g_sc_form.getValue(varVal);
			alert(varValue);
            if (varValue.toString() != 'true' && varValue.toString() != 'false') {
				//if (varValue != 'true' && varValue != 'false') {
                // now we need to call a custom GlideAJAX to fetch the translations
                var callTrans = new GlideAjax('variable_translate_sc');
                callTrans.addParam('sysparm_name', 'getTranslation');
                callTrans.addParam('sysparm_string', varValue.toString()); //.toString()
                callTrans.addParam('sysparm_variable', theVarsArr[v1].toString()); //.toString()
                callTrans.addParam('sysparm_task', g_form.getUniqueValue().toString()); //.toString()
                callTrans.getXML(translationParse);
            }
        }
		//});
    } catch (err) {
        alert('Error in Test - ' + err + ' - ' + err.message);
    }
}


function translationParse(response) {
    try {
		var output = '';
        var valResponse = response.responseXML.getElementsByTagName("result");
        for (var i = 0; i < valResponse.length; i++) {
            var name = valResponse[i].getAttribute("variable");
            var value = valResponse[i].getAttribute("value");
            //output += name + " = " + value + "\n ";
			if(name != 'null' || name != null){
				g_sc_form.showFieldMsg(name, value);
			}
        }
    } catch (err) {
        alert('Error in translationParse - ' + err.name + ' - ' + err.message);
    }
}

 

 

 

Script Include

var variable_translate_sc = Class.create();
variable_translate_sc.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	
 getTranslation: function() {
        try {
			var result = this.newItem("result");
            var theVar = this.getParameter('sysparm_variable'); // variable ID
            var string = this.getParameter('sysparm_string'); // the string to translate
            var taskSys = this.getParameter('sysparm_task'); // task record for gr'ing to get the text
            string = string.toString();
            // we need to include a few other scripts
            gs.include('LFTranslateUtils'); // this is mandatory

            // we need to know which translator is used for DT
            var usedTranslator = '';
            var getTranslator = new GlideRecord('sn_dt_translator_configuration');
            getTranslator.addEncodedQuery('default_provider=true');
            getTranslator.query();
            if (getTranslator.next()) {
                usedTranslator = getTranslator.name.toString();
            }

            var getString = new GlideRecord('sc_item_option_mtom');
            getString.addEncodedQuery('request_item.sys_id=' + taskSys + '^sc_item_option.value=' + string);
            getString.query();
            if (getString.next()) {
                var detectedResponse = sn_dt_api.DynamicTranslation.getDetectedLanguage(getString.sc_item_option.value.toString());
                var respStr = JSON.stringify(detectedResponse);
                var respE = new JSON().decode(respStr);
                var strLang = respE.detectedLanguage.name.toString();
                if (strLang != gs.getSession().getLanguage()) {
                    var getTranslation = JSON.stringify(sn_dt_api.DynamicTranslation.getTranslation(getString.sc_item_option.value.toString()), {
                        "targetLanguages": gs.getSession().getLanguage(),
                        "additionalParameters": [{
                            "parameterName": "texttype",
                            "parameterValue": "plain"
                        }],
                        "translator": usedTranslator
                    });
                    var gTransObj = JSON.parse(getTranslation, function(key, value) {
                        if (key == 'translatedText') {
							result.setAttribute("value", value.toString()+ gs.getMessage(" - Translated by ")+usedTranslator.toString());
							result.setAttribute("variable", theVar.toString());
                            return result;
                        }
                    });
                }
            }
        } catch (err) {
            gs.log('Error in variable_translate_sc.getTranslation - ' + err.name + ' - ' + err.message);
        }
    },
	
    type: 'variable_translate_sc'
});

 

 

3 REPLIES 3

Ankur Bawiskar
Tera Patron
Tera Patron

@Eheitman 

please share the script include script as well

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Ankur Bawiskar
Tera Patron
Tera Patron

@Eheitman 

client side code doesn't allow current object

why are you translating them via script? Is that not happening OOB when user with particular language opens the RITM form?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hello,

 

I have added the script include and edited my code to the current version. What I am trying to do here is allow Agents to Translate the Variables in the Variable Editor so that is not happening OOB. I was following this article from Alex Coope

 

My first 2 Client Side functions are working as expected, and the script include is working as expected, just not all together. My question has turned into, how do I call the variableTranslate() function properly after the getVarStr loop? If I put it inside to loop it runs too many times, if it is after the function ends it doesn't call it at all. 

 

Thanks