logo

NJP

"Set Value from Label" Tool

Import · Oct 12, 2018 · article

Included in the Developer Toolbox Update Set available on Share (link to Share in the post).

Another one of those lazy/productivity tools with a similar function:

As a general rule, I'll set the Value field to a lowercase version of the Label field because it makes it easier to use when comparing the strings in script. This tool will do that for me automatically. It will also prefix the string with the value of the Dependent value field.

Any special characters are replaced with an underscore character (anything other than a-z, 0-9).

image

Here are the details of the UI Action

Name: Set Value from Label

Table: Choice [sys_choice]

Order: 100,000

Action name: u_fpc_set_value_from_label

Active: checked

Show insert: checked

Show update: checked

Client: checked

Form link: checked

Hint: Create a string for the Value field based on the Label and Dependent value fields (FPC)Messages: u_fpc_set_value_from_label.confirm u_fpc_set_value_from_label.error.field.empty

u_fpc_set_value_from_label.message.populated

Onclick: uFpcSetValueFromLabel();

Condition: current.canWrite();

Script:

function uFpcSetValueFromLabel() {
    //hide previous field messages
    try {
        g_form.hideFieldMsg("value", true);
    } catch(err) {}

    //check to see if the Label field is populated or not
    var label = (g_form.getValue("label").toLowerCase()).trim();
    if (label == ""){
        g_form.showFieldMsg("value", getMessage("u_fpc_set_value_from_label.error.field.empty"), "error");
        return;
    }

    //make sure the user wants to replace the Value field
    if (g_form.getValue("value").trim() != ""){
        if (!confirm(getMessage("u_fpc_set_value_from_label.confirm")))
            return;
    }

    var value = (g_form.getValue("dependent_value").toLowerCase().replace(/[^a-z0-9]/g, "_")).trim();
    value += "_" + (label.toLowerCase().replace(/[^a-z0-9]/g, "_")).trim();
    value = value.replace(/_+/g,"_");   // replaces any one or more instances of "__" with only one "_"
    value = value.replace(/^\_+|\_+$/g, "");   // replaces all leading or trailing "_" with an empty string
    g_form.setValue("value", value);
    g_form.showFieldMsg("value", getMessage("u_fpc_set_value_from_label.message.populated"), "info");
}

I've attached XML files for the UI Action and UI Messages so you can just import them into your instance. As always, try it out in your company's development instance first, or better yet, your own personal development instance.

I've standardized on using UI Messages now for any message visible to users to make it easier to localize the tools.

View original source

https://www.servicenow.com/community/developer-blog/quot-set-value-from-label-quot-tool/ba-p/2265882