Modal not showing

NMMZ10
Tera Contributor

Hello,
I'm working on a development that is basically a button on the Changes List for the user to cancel multiple records, on click should open a modal so the user can insert a comment. And when submitted the comments are posted in work notes and close notes. 
So this gives the user the ability to cancel multiple records at once.

However the modal opens but nothing really happens.

NMMZ10_0-1767870023203.png

The cancel button doesnt do anything  

This is what i have so far
UI Action 

function changeState() {
    var ids = (g_list.getChecked() || '').toString();
    if (!ids) {
        gsftErrorMessage('Please select at least one Change Request.');
        return;
    }

    var gm = new GlideModal('cancel_cr_modal');
    gm.setTitle('Cancel selected Change Requests');
    gm.setPreference('sys_ids', ids);
    gm.setPreference('count', ids.split(',').length);
    gm.setWidth(700);
    gm.render();
}


Script Include

var cancelChangeState = Class.create();
cancelChangeState.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    changeState: function() {
        if (!gs.hasRole('change_manager')) {
            return JSON.stringify({
                ok: false,
                message: 'Not authorized (requires change_manager).'
            });
        }

        var sysIds = (this.getParameter('sysparm_sys_ids') || '').toString().trim();
        var comment = (this.getParameter('sysparm_comment') || '').toString().trim();

        if (!sysIds) {
            return JSON.stringify({
                ok: false,
                message: 'No records selected.'
            });
        }
        if (!comment) {
            return JSON.stringify({
                ok: false,
                message: 'Comment is mandatory.'
            });
        }

        var idList = sysIds.split(',').map(function(x) {
            return x.trim();
        }).filter(Boolean);

        var canceledVal = this._getChoiceValue('change_request', 'state', 'Canceled');
        if (!canceledVal) canceledVal = this._getChoiceValue('change_request', 'state', 'Cancelled');
        if (!canceledVal) {
            return JSON.stringify({
                ok: false,
                message: 'Unable to resolve the Canceled/Cancelled state value from sys_choice.'
            });
        }

        var gr = new GlideRecord('change_request');
        gr.addQuery('sys_id', 'IN', idList);

        if (gr.isValidField('type')) gr.addQuery('type', 'standard');
        if (gr.isValidField('std_change_producer')) {
            gr.addNotNullQuery('std_change_producer');
        } else if (gr.isValidField('std_change_template')) {
            gr.addNotNullQuery('std_change_template');
        } else if (gr.isValidField('sc_template')) {
            gr.addNotNullQuery('sc_template');
        }

        gr.query();

        var updated = 0;
        var skipped = [];

        while (gr.next()) {
            try {
                if ('' + gr.getValue('state') === '' + canceledVal) {
                    skipped.push(gr.getUniqueValue());
                    continue;
                }

                if (gr.isValidField('work_notes')) gr.setValue('work_notes', comment);
                if (gr.isValidField('close_notes')) gr.setValue('close_notes', comment);

                if (gr.isValidField('close_code')) {
                    var cc =
                        this._getChoiceValue('change_request', 'close_code', 'Canceled') ||
                        this._getChoiceValue('change_request', 'close_code', 'Cancelled') ||
                        '';
                    if (cc) gr.setValue('close_code', cc);
                }

                gr.setValue('state', canceledVal);
                gr.update();
                updated++;
            } catch (e) {
                skipped.push(gr.getUniqueValue());
            }
        }

        return JSON.stringify({
            ok: true,
            updated: updated,
            skipped: skipped
        });
    },

    _getChoiceValue: function(table, element, label) {
        var sc = new GlideRecord('sys_choice');
        sc.addQuery('name', table);
        sc.addQuery('element', element);
        sc.addQuery('label', label);
        sc.query();
        if (sc.next()) return '' + sc.getValue('value');
        return '';
    },

    type: 'cancelChangeState'
});

 UI Page HTML

<j:jelly xmlns:j="jelly:core" xmlns:g="glide" xmlns:ui="http://www.glide.com/ui.jelly">
    <div style="padding: 16px; max-width: 700px;">
        <h2>Cancel selected Change Requests</h2>
        <p>
            <strong>Selected:</strong> ${count}
            <br />
            Only Change Requests created from <em>Standard Change templates</em> will be canceled.
        </p>

        <div class="form-group" style="margin-top: 12px;">
            <label for="comment">Comment <span style="color:#d9534f;">(mandatory)</span></label>
            <textarea id="comment" class="form-control" rows="6" placeholder="Provide a clear reason for cancellation. This will be recorded in Work notes and Close notes."></textarea>
        </div>

        <div style="margin-top: 16px;">
            <button class="btn btn-danger" onclick="submitCancel()">Cancel Requests</button>
            <button class="btn btn-default" onclick="closeModal()">Close</button>
        </div>
    </div>

    <script type="text/javascript">

    </script>
</j:jelly>

UI Page Client Script

function closeModal() {
    try {
        GlideDialogWindow.get().destroy();
    } catch (e) {}
}

function submitCancel() {
    var comment = (document.getElementById('comment').value || '').trim();
    if (!comment) {
        GlideUI.get().addErrorMessage('Comment is mandatory to cancel the request(s).');
        return;
    }

    var ga = new GlideAjax('cancelChangeState');
    ga.addParam('sysparm_name', 'changeState');
    ga.addParam('sysparm_sys_ids', '${sys_ids}');
    ga.addParam('sysparm_comment', comment);

    ga.getXMLAnswer(function(answer) {
        var res;
        try {
            res = JSON.parse(answer || '{}');
        } catch (e) {
            GlideUI.get().addErrorMessage('Unexpected server response. Please check logs.');
            return;
        }

        var msg;
        if (res.ok) {
            var updated = (res.updated || 0);
            var skippedCount = (res.skipped && res.skipped.length) ? res.skipped.length : 0;
            msg = 'Canceled ' + updated + ' Change Request(s).';
            if (skippedCount) {
                msg += ' Skipped: ' + skippedCount + '.';
            }
            GlideUI.get().addInfoMessage(msg);
            closeModal();
            if (typeof g_list !== 'undefined') {
                g_list.refresh();
            }
        } else {
            GlideUI.get().addErrorMessage(res.message || 'Update failed.');
        }
    });
}

i cannot seem to understand why its not working.
Any help is welcome.
Thanks

3 REPLIES 3

DineshK24367716
Mega Guru

Hi @NMMZ10 ,

Your whole script is completely fine but the one thing you need to change the script is : In UI Action Script whenever you are setting preferences using SetPreference Method you need to use variable names as sysparm_sys_ids and sysparm_count

function changeState() {
    var ids = (g_list.getChecked() || '').toString();
    if (!ids) {
        gsftErrorMessage('Please select at least one Change Request.');
        return;
    }

    var gm = new GlideModal('cancel_cr_modal');
    gm.setTitle('Cancel selected Change Requests');
    gm.setPreference('sysparm_sys_ids', ids);
    gm.setPreference('sysparm_count', ids.split(',').length);
    gm.setWidth(700);
    gm.render();
}

and get those variables in UI Script Using the same names.
If my response help, mark my solution as accepted so that it can be helpful for the future readers.

 

What UI Script do you mean? in the UI page? 

The modal already appears but now the cancel buttons doesnt really do anything

@NMMZ10 ,

Yes first change the variable names in UI Action Script as how i mentioned in my above post.

And in the UI Page Script, use those variables names only to get the count and the sysids

function closeModal() {
    try {
        GlideDialogWindow.get().destroy();
    } catch (e) {}
}

function submitCancel() {
    var comment = (document.getElementById('comment').value || '').trim();
    if (!comment) {
        GlideUI.get().addErrorMessage('Comment is mandatory to cancel the request(s).');
        return;
    }

    var ga = new GlideAjax('cancelChangeState');
    ga.addParam('sysparm_name', 'changeState');
    ga.addParam('sysparm_sys_ids', '${sysparm_sys_ids}');
    ga.addParam('sysparm_comment', comment);

    ga.getXMLAnswer(function(answer) {
        var res;
        try {
            res = JSON.parse(answer || '{}');
        } catch (e) {
            GlideUI.get().addErrorMessage('Unexpected server response. Please check logs.');
            return;
        }

        var msg;
        if (res.ok) {
            var updated = (res.updated || 0);
            var skippedCount = (res.skipped && res.skipped.length) ? res.skipped.length : 0;
            msg = 'Canceled ' + updated + ' Change Request(s).';
            if (skippedCount) {
                msg += ' Skipped: ' + skippedCount + '.';
            }
           addFormMessage(msg, "info", 0); 
            closeModal();
            if (typeof g_list !== 'undefined') {
                g_list.refresh();
            }
        } else {
          var msg=res.message || 'Update failed.';
           addFormMessage(msg, "error", 0); 
         closeModal();
        }
    });

Just copy paste the above script in your ui page client script 

Why it not works in your case is in the Script you used 

GlideUI.get().addInfoMessage(msg) , it didn't work in list view so i changed that and updated .Now the code is working fine 
If my response help, mark my solution as accepted so that it can be helpful for the future readers.