Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

Value not getting saved in "sp-variable-editor" from portal

Hafsa1
Mega Sage

I have made "sp-variable-editor" editable for CMS table(sn_customerservice_case).

But when I'm saving the variable then it is not getting saved. I'm using OOB widget sp-variable-editor

 

Hafsa1_0-1739063438928.png

 

HTML

<div ng-class="{'panel panel-default': !data.hide_container}" ng-if="::c.hasVariables(data.sc_cat_item._fields) && !c.options.isServiceWorkspace">
<div class="panel-heading" ng-if="!data.hide_container">
<h3 ng-if="data.itemTitle" class="panel-title">{{data.itemTitle}}</h3>
<h3 ng-if="!data.itemTitle" class="panel-title">{{data.vEditorLabel}}</h3>
</div>
<div ng-class="{'panel-body': !data.hide_container, 'variable-editor': data.hide_container}">
<sp-model form-model="::data.sc_cat_item" mandatory="[]"></sp-model>
</div>
<div ng-if="c.showSave && c.options.readonly_variable_editor != 'true'" class="panel-footer">
<button class="btn btn-primary pull-right" name="save" ng-click="c.save()">${Save}</button>
<span ng-if="validating" style="padding-left:4px">${Validating...}</span>
<div style="clear: both;"></div>
</div>
</div>
<div class="workspace-variables" ng-if="::c.hasVariables(data.sc_cat_item._fields) && c.options.isServiceWorkspace">
<div class="variables">
<sp-model form-model="::data.sc_cat_item" mandatory="[]"></sp-model>
</div>
<div ng-if="c.showSave && c.options.readonly_variable_editor != 'true'">
<button class="btn btn-primary pull-right" name="save" ng-click="c.save()">${Save}</button>
<span ng-if="validating" style="padding-left:4px">${Validating...}</span>
<div style="clear: both;"></div>
</div>
</div>
<div ng-if="::!c.hasVariables(data.sc_cat_item._fields)">
<h4 class="text-a-c">
{{::c.data.msg}}
</h4>
</div>
<now-message key="Variable saved" value="${Form is saved, to submit the form kindly add comments and click on 'SEND' button}"></now-message>

 

Server script :

(function() {

    data.table = options.table || $sp.getParameter("table");
    data.sys_id = options.sys_id || $sp.getParameter("sys_id") || $sp.getParameter("sl_sys_id");
    data.msg = gs.getMessage('There are no variables associated');
    data.hide_container = options.hide_container;
    data.vEditorLabel = gs.getMessage('Variables');
    if (input) {
        var vars = [];
        var fields = input.sc_cat_item._fields;
        data.sys_id = input.sys_id;
        data.table = input.table;
        if (!data.table || !data.sys_id)
            return;

        var values = getValues(data.table, data.sys_id);
        for (var v in fields) {
            // 12: Break, 19: Container Start, 20: Container End, 24: Container Split
            if (values[f].type == 12 || values[f].type == 19 || values[f].type == 20 || values[f].type == 24)
                    continue;
            vars.push(fields[v]);
        }

        if (data.table == "sc_cart_item")
            SPCart.updateItem(input.sys_id, vars);
        else
            $sp.saveVariables(input.table, input.sys_id, vars);
        return;
    }
   
    if (!data.table || !data.sys_id) {
        return;
    }

    var gr = $sp.getRecord(data.table, data.sys_id);
    if (gr.isValid() && gr.canRead()) {
        var targetTable = data.table;
        if (targetTable == "sc_cart_item")
            targetTable = "sc_cat_item";
        var req_id = "";
        var task_id = "";
        var sys_id = "";
        var table_id = "";
        var opened_by= "";
        if(data.table == 'sc_task') {
            req_id = gr.request_item.getValue();
            task_id = data.sys_id;
            sys_id = gr.request_item.cat_item.getValue();
            opened_by = gr.opened_by.getValue();
        } else if(data.table == 'sc_req_item') {
            req_id = data.sys_id;
            sys_id = gr.cat_item.getValue();
            opened_by = gr.opened_by.getValue();
        } else if(data.table == 'sc_cart_item') {
            sys_id = gr.cat_item.getValue();
            req_id = gr.getUniqueValue();
        } else if (gr.instanceOf("task")) {
            targetTable = data.table;
            table_id = data.sys_id;
            opened_by = gr.opened_by.getValue();
            var catItemProducedGr = new GlideRecord("sc_item_produced_record");
            catItemProducedGr.addQuery("record_key", data.sys_id);
            catItemProducedGr.query();
            if (catItemProducedGr.next())
                sys_id = catItemProducedGr.getValue("producer");
        } else {
            sys_id = gr.request_item.cat_item.getValue();
        }
        var filter = {
            sys_id : String(sys_id),
            request_id : String(req_id),
            task_id : String(task_id),
            table: String(targetTable),
            table_id: String(table_id),
            opened_by : String(opened_by)
        };
        if (gr.isValidField("variables"))
            data.vEditorLabel = gr.getElement("variables").getLabel();
        data.sc_cat_item = $sp.getCatalogItem(filter);
        if (options.showItemTitle)
            data.itemTitle = data.sc_cat_item.short_description;
        var values = {};
        if (data.table == 'sc_task' || data.table == 'sc_req_item' || data.table == 'sc_cart_item') {
            values = getValues(data.table, req_id, task_id, opened_by);
        } else {
            // Other task extensions
            values = getValuesForProducer(data.table, data.sys_id, opened_by);
        }
        data.values = values;
        var isQuestionReadOnly = ((options.readonly_variable_editor == 'true') || ((gs.getProperty('glide.sc.evaluate.variables.write.access', true) == 'true') ? !gr.variables.canWrite() : !gr.canWrite()));

        for(var f in data.sc_cat_item._fields) {
            // (isQuestionReadOnly)
//data.sc_cat_item._fields[f].sys_readonly = true;
           
            //  Adding table_name for attachment variables
            if (data.sc_cat_item._fields[f].type == 'sc_attachment') {
                data.sc_cat_item._fields[f].recordTableName = data.table;
                data.sc_cat_item._fields[f].recordSysId = data.sys_id;
            }
           
            // Put the values into the cat item fields
            if (typeof values[f] != "undefined") {
                if (values[f].type == 12 || values[f].type == 19 || values[f].type == 20 || values[f].type == 24)
                    continue;
                if (typeof values[f].value != "undefined") {
                    if (values[f].type == 9 || values[f].type == 10)
                        data.sc_cat_item._fields[f].value = values[f].displayValue;
                    else if (values[f].type == 25 && data.sc_cat_item._fields[f].catalog_view_masked)
                        data.sc_cat_item._fields[f].value = values[f].decrypted_value;
                    else
                        data.sc_cat_item._fields[f].value = values[f].value;
                    data.sc_cat_item._fields[f].displayValue = values[f].displayValue;
                    data.sc_cat_item._fields[f].display_value_list = values[f].display_value_list;
                }
            }
        }
    } else
        data.msg = gs.getMessage('You are either not authorized or record is not valid');
   
    function getValues(table, sys_id, task_id, opened_by) {
        var qs = new GlideappVariablePoolQuestionSet();
        if (table == "sc_cart_item")
            qs.setCartID(sys_id);
        else if(table == "sc_task") {
            qs.setRequestID(sys_id);
            qs.setTaskID(task_id);
        } else {
            qs.setRequestID(sys_id);
        }
       
        qs.load();
        var values = {};
        var questions = qs.getFlatQuestions().toArray();
        for (var i = 0; i < questions.length; i++) {
            var q = questions[i];
            var o = {value: q.getValue(), displayValue: q.getDisplayValue(), type: q.getType()};
            //handling List Collector (21) and Masked (25) variables.
            if (o.type == 21)
                o.display_value_list = q.getDisplayValues().toArray();
            if (o.type == 25 && q.canDecrypt(opened_by, table))
                o.decrypted_value = q.decrypt(o.value);
            var qKey = q.getName();
            if (typeof qKey == 'undefined' || qKey == '')
                qKey = "IO:" + q.getId();
            values[qKey] = o;
        }
        return values;
    }
   
    function getValuesForProducer(table, sys_id, opened_by) {
        var qs = new GlideappSequencedQuestionSet();
        qs.setTableName(table);
        qs.setTableSysID(sys_id);
       
        qs.load();
        var values = {};
        var questions = qs.getFlatQuestions().toArray();
        for (var i = 0; i < questions.length; i++) {
            var q = questions[i];
            var o = {value: q.getValue(), displayValue: q.getDisplayValue(), type: q.getType()};
            //handling List Collector (21) and Masked (25) variables.
            if (o.type == 21)
                o.display_value_list = q.getDisplayValues().toArray();
            if (o.type == 25 && q.canDecrypt(opened_by, table))
                o.decrypted_value = q.decrypt(o.value);
            var qKey = q.getName();
            if (typeof qKey == 'undefined' || qKey == '')
                qKey = "IO:" + q.getId();
            values[qKey] = o;
        }
        return values;
    }
   
 
})();

CLient controller:

function($scope, $document, $rootScope, i18n, spScUtil) {
  /* widget controller */
  var c = this;
    c.isSaved = false;
    var parent_g_form = $scope.page.g_form;
    var origActionName;

    if (!parent_g_form)
        c.showSave = true;
   
    c.getItemId = function () {
        return $scope.data.sc_cat_item ? $scope.data.sc_cat_item.sys_id : -1;
    };

    var g_form;
    $scope.$on('spModel.gForm.initialized', function(e, gFormInstance){
        if (gFormInstance.getSysId() != -1 && gFormInstance.getSysId() != c.getItemId())
            return;

        if (parent_g_form)
            addSaveHandler();

        g_form = gFormInstance;
        g_form.$private.events.on('submitted', function() {
                if (!c.showSave) {
                    c.server.update().then(function() {
                        parent_g_form.submit(origActionName);
                        c.isSaved = true;
                    });
                }
                else {
                c.server.update().then(function() {
                    //start
                //g_form.addInfoMessage(i18n.getMessage('Variable saved'));
                confirm(i18n.getMessage('Variable saved'));
                    //end
                if (c.options.isServiceWorkspace == true) { //Workspace handler
                    if (window.parent === window) {
                        console.warn("Parent is missing. Is this called inside an iFrame?");
                        return;
                    }
                    window.parent.postMessage({
                            messageType: 'IFRAME_MODAL_MESSAGE_TYPE',
                            modalAction: 'IFRAME_MODAL_ACTION_CONFIRMED',
                            modalId: 'sn-modal-iframe-singleton'
                    }, location.origin)
                }
                if (c.data.table == "sc_cart_item")
                    $rootScope.$broadcast("$sp.service_catalog.cart.update");
                });
            }
        })
    });

    // Used when embedded as a formatter
    function addSaveHandler() {
        parent_g_form.$private.events.on("submit", function() {
            var actionName = parent_g_form.getActionName();
            // If actionName is none, form has already been re-submitted.
            // No need to submit it the third time.
            if (actionName === 'none') { return false; }

            origActionName = actionName;
            if (c.isSaved) return true;

            if (!spScUtil.isServerValidationDone($scope.data.sc_cat_item._fields)) {
                $scope.validating = true;
                return false;
            }

            if (g_form)
                return g_form.submit();
            return true;
        });
        parent_g_form.$private.events.on("submitted", function() {
            c.isSaved = false;
        });
    }

    c.save = function() {
        var activeElement = $document.activeElement;
        if (activeElement)
            activeElement.blur();
        if (!spScUtil.isServerValidationDone($scope.data.sc_cat_item._fields))
            $scope.validating = true;

        else if (g_form)
            g_form.submit();        
    };
    c.hasVariables = function(fields) {
        if (!fields)
            return false;
       
        return Object.keys(fields).length > 0;
    }

    var validationComplete = $rootScope.$on('$sp.service_catalog.form_validation_complete', function() { $scope.validating = false; });
}
5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@Hafsa1 

what changes you made to the OOB Widget so that it allows saving?

share those from the above script

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

@Ankur Bawiskar 

 

HTML- message value was changed as below

<now-message key="Variable saved" value="${Form is saved, to submit the form kindly add comments and click on 'SEND' button}"></now-message>

 

Server script: below line was commented to make all variables editable
// (isQuestionReadOnly)
//data.sc_cat_item._fields[f].sys_readonly = true;

 

client controller: below message type changed from infomessage to confirm box
//g_form.addInfoMessage(i18n.getMessage('Variable saved'));
                confirm(i18n.getMessage('Variable saved'));

Hafsa1
Mega Sage

@Ankur Bawiskar 

even when I"m using OOB it is not saving/changing variables

@Hafsa1 

this is on which portal page? ticket page?

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