Suitelet for Brandscope setup form.

Jira Code: BPL-5

Created a new suitelet brandscope setup form. The form contains body fields and sublists. On body fields in save action new custom record is created. Added 2 buttons for location and brand. When we click ‘Add location’ button, then a new window opens and it allows to add locations and abbreviations. And by clicking the ‘save’ button, the added location is updated on the Brandscope setup form in LOCATION sublist. There is another button ‘add brand’, while clicking that, it opens a new window and allows to add location and brand. While saving it , the added brand will update on the Brandscope form in BRAND sublist.

Client Script

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/**
 * Script Description
 *  Brandscope setup - Brandscope Report
 */
/*******************************************************************************
 * Brandscope Pty Ltd
 * **************************************************************************
 * 
 * Date: 03/03/2019
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 * 
 * REVISION HISTORY
 * 
 * Revision 1 $ 03/03/2019 Maria: Create
 * 
 ******************************************************************************/
var BRANDSCOPE_SETUP;
define(['N/record', 'N/search', 'N/runtime', 'N/url', 'N/currentRecord', 'N/https'],

    function(record, search, runtime, url, currentRecord, https) {

        /**
         * Function to be executed after page is initialized.
         *
         * @param {Object} scriptContext
         * @param {Record} scriptContext.currentRecord - Current form record
         *
         * @since 2015.2
         */
        function pageInit(scriptContext) {

            window.onbeforeunload = function() {

            };
            window.onunload = function() {

                window.opener.location.reload();
            };
        }

        //defining actions for edit button
        function editBtnAction() {

            try {
                var get_url;

                get_url = url.resolveScript({
                    scriptId: 'customscript_jj_bpl2_sl_brandscope_setup',
                    deploymentId: 'customdeploy_jj_bpl2_id_setup',
                    returnExternalUrl: false
                });

                get_url += '&Edit=TRUE';
                window.location.href = get_url;

            } catch (e) {
                console.log(e.name, e.message);
            }
        }

        // Defining functions to cancel button
        function cancel() {

            try {

                get_cancelurl = url.resolveScript({
                    scriptId: 'customscript_jj_bpl2_sl_brandscope_setup',
                    deploymentId: 'customdeploy_jj_bpl2_id_setup',
                    returnExternalUrl: false
                });
                //console.log("success21");
                window.location.href = get_cancelurl;

            } catch (e) {
                console.log(e.name, e.message);
            }
        }

        //defining actions for location
        function locationBtnAction() {

            try {
                var get_url;

                get_url = url.resolveScript({
                    scriptId: 'customscript_jj_bpl2_sl_brandscpe_loctn',
                    deploymentId: 'customdeploy_jj_bpl2_brandscpe_location',
                    returnExternalUrl: false
                });

                get_url += '&Loca=TRUE';
                window.open(get_url, "Component Quantity Calculator", 'height=500,width=1000')


            } catch (e) {
                console.log(e.name, e.message);
            }
        }

        //defining actions for Brand
        function locationsaveBtnAction() {

            try {
                var count = 0;
                var CurrRecord = currentRecord.get();
                console.log("CurrRecord", CurrRecord);

                var sublistcount = CurrRecord.getLineCount({
                    sublistId: "custpage_brandscope_location_sublist"
                });

                var currentAbbrevations = {};

                for (var j = 0; j < sublistcount; j++) {

                    currentAbbrevations[CurrRecord.getSublistValue({
                        sublistId: 'custpage_brandscope_location_sublist',
                        fieldId: 'custpage_brandscope_location',
                        line: j
                    })] = CurrRecord.getSublistValue({
                        sublistId: 'custpage_brandscope_location_sublist',
                        fieldId: 'custpage_brandscope_location_abbr',
                        line: j
                    });

                }

                var locJSON = JSON.stringify(currentAbbrevations);

                jQuery("#custpage_load_img").css("display", "block");

                https.post.promise({
                        url: url.resolveScript({
                            scriptId: 'customscript_jj_bpl2_sl_brandscpe_loctn',
                            deploymentId: 'customdeploy_jj_bpl2_brandscpe_location',
                            returnExternalUrl: false
                        }),
                        body: locJSON
                    })
                    .then(function(response) {

                        window.close();

                        log.debug({
                            title: 'Response',
                            details: response
                        });
                    })
                    .catch(function onRejected(reason) {
                        log.debug({
                            title: 'Invalid Request: ',
                            details: reason
                        });
                    })


            } catch (e) {
                console.log(e.name, e.message);
            }
        }

        // To close the window
        function locationcancelBtnAction() {
            try {

                window.close();

            } catch (e) {
                console.log(e.name, e.message);
            }

        }

        //defining actions for brand
        function brandBtnAction() {

            try {
                var get_url;

                get_url = url.resolveScript({
                    scriptId: 'customscript_jj_bpl2_brandscope_brand',
                    deploymentId: 'customdeploy_jj_bpl2_brandscope_brandset',
                    returnExternalUrl: false
                });

                get_url += '&Brand=TRUE';
                window.open(get_url, "Component Quantity Calculator", 'height=500,width=1000')


            } catch (e) {
                console.log(e.name, e.message);
            }
        }

        function brandsaveBtnAction() {

            try {
                var count = 0;
                var CurRecord = currentRecord.get();

                var sublistcount = CurRecord.getLineCount({
                    sublistId: "custpage_brandscope_brand_sublist"
                });

                var currentlocation = {},
                    currentbrand = {};

                for (i = 0; i < sublistcount; i++) {
                    //currentlocation[loc][brand]=true ==> currentlocation={loc:{brand:true}}
                    if (!currentlocation[CurRecord.getSublistValue({
                            sublistId: 'custpage_brandscope_brand_sublist',
                            fieldId: 'custpage_brandscope_location_brand',
                            line: i
                        })])
                        currentlocation[CurRecord.getSublistValue({
                            sublistId: 'custpage_brandscope_brand_sublist',
                            fieldId: 'custpage_brandscope_location_brand',
                            line: i
                        })] = {};

                    currentlocation[CurRecord.getSublistValue({
                        sublistId: 'custpage_brandscope_brand_sublist',
                        fieldId: 'custpage_brandscope_location_brand',
                        line: i
                    })][CurRecord.getSublistValue({
                        sublistId: 'custpage_brandscope_brand_sublist',
                        fieldId: 'custpage_brandscope_brand',
                        line: i
                    })] = true;

                }

                var brandJSON = JSON.stringify(currentlocation);

                jQuery("#custpage_load_img").css("display", "block");
                https.post.promise({
                        url: url.resolveScript({
                            scriptId: 'customscript_jj_bpl2_brandscope_brand',
                            deploymentId: 'customdeploy_jj_bpl2_brandscope_brandset',
                            returnExternalUrl: false
                        }),
                        body: brandJSON
                    })
                    .then(function(response) {

                        window.close();

                        log.debug({
                            title: 'Response',
                            details: response
                        });
                    })
                    .catch(function onRejected(reason) {
                        log.debug({
                            title: 'Invalid Request: ',
                            details: reason
                        });
                    })              

            } catch (e) {
                console.log(e.name, e.message);
            }

        }


        // To close the window
        function brandcancelBtnAction() {
            try {

                window.close();

            } catch (e) {
                console.log(e.name, e.message);
            }

        }        

        /*******************************************************************************
         * return error
         * 
         * @param e
         * @returns
         */
        function getError(e) {
            var stErrMsg = '';
            if (e.getDetails != undefined) {
                stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
                    e.getStackTrace();
            } else {
                stErrMsg = '_' + e.toString();
            }
            return stErrMsg;
        }

        /*******************************************************************************
         * Log these data
         * 
         * @param title
         * @param details
         * @returns
         */
        function logme(title, details) {
            log.debug({
                title: title,
                details: details
            });
        }


        return {
            pageInit: pageInit,
            editBtnAction: editBtnAction,
            cancel: cancel,
            locationBtnAction: locationBtnAction,
            locationsaveBtnAction: locationsaveBtnAction,
            locationcancelBtnAction: locationcancelBtnAction,
            brandBtnAction: brandBtnAction,
            brandsaveBtnAction: brandsaveBtnAction,
            brandcancelBtnAction: brandcancelBtnAction           
        };

    });

Suitelet:

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/**
 * Script Description
 *  Brandscope setup - Brandscope Report
 */
/*******************************************************************************
 * Brandscope Pty Ltd
 * **************************************************************************
 * 
 * Date: 01/03/2019
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 * 
 * REVISION HISTORY
 * 
 * Revision 1 $ 01/03/2019 Maria: Create
 * 
 ******************************************************************************/
define(['N/http', 'N/record', 'N/redirect', 'N/search', 'N/ui/serverWidget', 'N/redirect'],

    function(http, record, redirect, search, serverWidget, redirect) {

        /**
         * Definition of the Suitelet script trigger point.
         *
         * @param {Object} context
         * @param {ServerRequest} context.request - Encapsulation of the incoming request
         * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
         * @Since 2015.2
         */
        function onRequest(context) {

            try {
                var Edit = assignDefaultValue(context.request.parameters.Edit, 'FALSE');
                var Loca = assignDefaultValue(context.request.parameters.Loca, 'FALSE');

                //create form
                if (context.request.method === 'GET') {
                    var form = serverWidget.createForm({
                        title: 'BrandScope Setup'
                    });

                    //if(Edit == "TRUE"){
                    // Main area
                    var generalfields = form.addFieldGroup({
                        id: 'fieldgroupidgeneral',
                        label: 'General'
                    });
                    //create fields
                    var ats_token = form.addField({
                        id: 'custpage_brandscope_ats_token',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ATS TOKEN',
                        container: 'fieldgroupidgeneral'
                    });
                    ats_token.isMandatory = true;
                    ats_token.setHelpText({
                        help: "Enter the Unique Identifer"
                    });

                    /*var ats_page_size = form.addField({
                        id: 'custpage_brandscope_ats_page_size',
                        type: serverWidget.FieldType.INTEGER,
                        label: 'ATS PAGE SIZE',
                        container: 'fieldgroupidgeneral'
                    });
                    ats_page_size.isMandatory = true;*/

                    var ats_endpoint = form.addField({
                        id: 'custpage_brandscope_ats_endpoint',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ATS ENDPOINT',
                        container: 'fieldgroupidgeneral'
                    });
                    ats_endpoint.isMandatory = true;
                    ats_endpoint.setHelpText({
                        help: "This field is to enter ATS Endpoint url"
                    });

                    var email_sender = form.addField({
                        id: 'custpage_brandscope_ats_email_sender',
                        type: serverWidget.FieldType.SELECT,
                        source: 'employee',
                        label: 'EMAIL SENDER (EMPLOYEE)',
                        container: 'fieldgroupidgeneral'
                    });
                    email_sender.isMandatory = true;
                    email_sender.setHelpText({
                        help: "Enter the employee"
                    });


                    //Area for Item Field Information
                    var iteminformation = form.addFieldGroup({
                        id: 'fieldgroupiditeminformation',
                        label: 'Item Field Information',
                        isCollapsible: true
                    });
                    iteminformation.isCollapsible = true;

                    var integrationid = form.addField({
                        id: 'custpage_brandscope_integrationid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'INTEGRATION FIELD ID',
                        container: 'fieldgroupiditeminformation'
                    });
                    integrationid.isMandatory = true;
                    integrationid.setHelpText({
                        help: "This field is a unique ID. It is taken from the item record.If none is given, internalid is used as default"
                    });

                    var itemcolorid = form.addField({
                        id: 'custpage_brandscope_itemcolorid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ITEM COLOUR FIELD ID',
                        container: 'fieldgroupiditeminformation'
                    });
                    itemcolorid.isMandatory = true;
                    itemcolorid.setHelpText({
                        help: "Field ID from item record mentioned the color of the item"
                    });

                    var itemsizeid = form.addField({
                        id: 'custpage_brandscope_itemsizeid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ITEM SIZE FIELD ID',
                        container: 'fieldgroupiditeminformation'
                    });
                    itemsizeid.isMandatory = true;
                    itemsizeid.setHelpText({
                        help: "Field ID from item record mentioned the size of the item"
                    });

                    var itembrandid = form.addField({
                        id: 'custpage_brandscope_itembrandid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ITEM BRAND FIELD ID',
                        container: 'fieldgroupiditeminformation'
                    });
                    itembrandid.isMandatory = true;
                    itembrandid.setHelpText({
                        help: "Field ID from item record mentioned the brand of the item"
                    });

                    //Area for Date Field Information
                    var dateinformation = form.addFieldGroup({
                        id: 'fieldgroupiddateinformation',
                        label: 'Date Field Information',
                        isCollapsible: true
                    });
                    dateinformation.isCollapsible = true;

                    var exptd_ship_dateid = form.addField({
                        id: 'custpage_brandscope_exptd_ship_dateid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'EXPECTED SHIP DATE FIELD ID',
                        container: 'fieldgroupiddateinformation'
                    });
                    exptd_ship_dateid.isMandatory = true;
                    exptd_ship_dateid.setHelpText({
                        help: "The Date Field in Sales Order taken for ATS calculation. It is used to determine when the item fulfilled. If none is given, trandate is used as default"
                    });

                    var exptd_recvd_dateid = form.addField({
                        id: 'custpage_brandscope_exptd_recvd_dateid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'EXPECTED RECIEVED DATE FIELD ID',
                        container: 'fieldgroupiddateinformation'
                    });
                    exptd_recvd_dateid.isMandatory = true;
                    exptd_recvd_dateid.setHelpText({
                        help: "The Date Field in Purchase Order taken for ATS calculation. It is used to determine when the item received. If none is given, duedate is used as default"
                    });

                    var location_sublist_main = form.addSublist({
                        id: 'custpage_brandscope_location_sublist_main',
                        type: serverWidget.SublistType.STATICLIST,
                        label: 'LOCATION'
                    });
                    var location_main = location_sublist_main.addField({
                        id: 'custpage_brandscope_location_main',
                        type: serverWidget.FieldType.TEXT,
                        label: 'LOCATION',
                        source: 'location'
                    });

                    var location_abbr_main = location_sublist_main.addField({
                        id: 'custpage_brandscope_location_abbr_main',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ABBREVIATIONS'
                    });

                    //Area for Brand list ID Section
                    var btandlistid = form.addFieldGroup({
                        id: 'brandlistidfield',
                        label: 'Brand List ID',
                        isCollapsible: true
                    });
                    btandlistid.isCollapsible = true;

                    var brandlistid = form.addField({
                        id: 'custpage_brandscope_brandlistid',
                        type: serverWidget.FieldType.TEXT,
                        label: 'BRAND LIST ID',
                        container: 'brandlistidfield'
                    });
                    brandlistid.isMandatory = true;
                    brandlistid.setHelpText({
                        help: "Enetr the field ID of the list for the brand"
                    });


                    var location_array = locationsublistvalue();

                    if (location_array) {
                        var k = 0;
                        //var i=0;
                        // for(i=0;i<location_array.length;i++){
                        for (i = 0; i < location_array.length; i++) {

                            var loca_val = location_array[i];

                            for (var key in loca_val) {

                                if (loca_val[key].locationval) {
                                    location_sublist_main.setSublistValue({
                                        id: 'custpage_brandscope_location_main',
                                        line: k,
                                        value: loca_val[key].locationval
                                    });
                                }

                                if (loca_val[key].abbr_value) {
                                    location_sublist_main.setSublistValue({
                                        id: 'custpage_brandscope_location_abbr_main',
                                        line: k,
                                        value: loca_val[key].abbr_value
                                    });
                                }
                                k++;
                            }

                        }

                    }

                    var brand_sublist_main = form.addSublist({
                        id: 'custpage_brandscope_brand_sublist_main',
                        type: serverWidget.SublistType.STATICLIST,
                        label: 'BRAND'
                    });
                    var location_brand_main = brand_sublist_main.addField({
                        id: 'custpage_brandscope_location_brand_main',
                        type: serverWidget.FieldType.TEXT,
                        label: 'LOCATION',
                        source: 'location'
                    });

                    var customrecord479SearchObj = search.create({
                        type: "customrecord_jj_bpl2_cust_brandsetup",
                        filters: [],
                        columns: [
                            search.createColumn({
                                name: "scriptid",
                                sort: search.Sort.ASC,
                                label: "Script ID"
                            }),
                            search.createColumn({ name: "custrecord_jj_bpl2_brand_listid", label: "BRAND LIST ID" }),
                            search.createColumn({ name: "internalid", label: "Internal ID" })
                        ]
                    });
                    var searchResultCount = customrecord479SearchObj.runPaged().count;
                    //logme("customrecord479SearchObj result count", searchResultCount);
                    var searchResultCount = customrecord479SearchObj.runPaged().count;
                    var searchResults = customrecord479SearchObj.run().getRange({
                        start: 0,
                        end: 5
                    });

                    var searchResult_length = searchResults.length;

                    for (var i = 0; i < searchResult_length; i++) {

                        var searchResult = searchResults[i];

                        var brandlist = searchResult.getValue({
                            name: "custrecord_jj_bpl2_brand_listid",
                            label: "BRAND LIST ID"
                        });
                    }



                    var brand_main = brand_sublist_main.addField({
                        id: 'custpage_brandscope_brand_main',
                        type: serverWidget.FieldType.TEXT,
                        label: 'BRAND',
                        source: brandlist
                    });

                    var brand_array = brandsublistvalue();

                    if (brand_array) {

                        for (j = 0; j < brand_array.length; j++) {

                            if (brand_array[j].brandlocationval) {
                                brand_sublist_main.setSublistValue({
                                    id: 'custpage_brandscope_location_brand_main',
                                    line: j,
                                    value: brand_array[j].brandlocationval
                                });
                            }
                            if (brand_array[j].brand_value) {
                                brand_sublist_main.setSublistValue({
                                    id: 'custpage_brandscope_brand_main',
                                    line: j,
                                    value: brand_array[j].brand_value
                                });
                            }
                        }
                    }

                    var customrecord479SearchObj = search.create({
                        type: "customrecord_jj_bpl2_cust_brandsetup",
                        filters: [],
                        columns: [
                            search.createColumn({
                                name: "scriptid",
                                sort: search.Sort.ASC,
                                label: "Script ID"
                            }),
                            search.createColumn({ name: "custrecord_jj_bpl2_ats_token", label: "ATS TOKEN" }),
                            //search.createColumn({ name: "custrecord_jj_bpl2_ats_page_size", label: "ATS PAGE SIZE" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_email_sender", label: "EMAIL SENDER (EMPLOYEE)" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_ata_endpoint", label: "ATS ENDPOINT" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_integration_field_id", label: "INTEGRATION FIELD ID" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_item_color_fieldid", label: "ITEM COLOUR FIELD ID" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_item_size_fieldid", label: "ITEM SIZE FIELD ID" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_item_brand_fieldid", label: "ITEM BRAND FIELD ID" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_expected_ship_date", label: "EXPECTED SHIP DATE FIELD ID" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_expectd_rec_ship_date", label: "EXPECTED RECEIVED SHIP DATE FIELD ID" }),
                            search.createColumn({ name: "custrecord_jj_bpl2_brand_listid", label: "BRAND LIST ID" }),
                            search.createColumn({ name: "internalid", label: "Internal ID" })
                        ]
                    });
                    var searchResultCount = customrecord479SearchObj.runPaged().count;
                    //logme("customrecord479SearchObj result count", searchResultCount);
                    var searchResultCount = customrecord479SearchObj.runPaged().count;
                    var searchResults = customrecord479SearchObj.run().getRange({
                        start: 0,
                        end: 5
                    });

                    var searchResult_length = searchResults.length;

                    if (searchResult_length == 1) {
                        try {
                            for (var i = 0; i < searchResult_length; i++) {

                                var searchResult = searchResults[i];

                                var search_ats_token = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_ats_token",
                                    label: "ATS TOKEN"
                                });

                                /*var search_ats_page_size = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_ats_page_size",
                                    label: "ATS PAGE SIZE"
                                });*/

                                var search_email_sender = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_email_sender",
                                    label: "EMAIL SENDER (EMPLOYEE)"
                                });

                                var search_ata_endpoint = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_ata_endpoint",
                                    label: "ATS ENDPOINT"
                                });
                                //logme("search_ata_endpoint",search_ata_endpoint);

                                var search_integration_field_id = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_integration_field_id",
                                    label: "INTEGRATION FIELD ID"
                                });

                                var search_item_color_fieldid = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_item_color_fieldid",
                                    label: "ITEM COLOUR FIELD ID"
                                });

                                var search_item_size_fieldid = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_item_size_fieldid",
                                    label: "ITEM SIZE FIELD ID"
                                });

                                var search_item_brand_fieldid = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_item_brand_fieldid",
                                    label: "ITEM BRAND FIELD ID"
                                });

                                var search_expected_ship_date = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_expected_ship_date",
                                    label: "EXPECTED SHIP DATE FIELD ID"
                                });

                                var search_expectd_rec_ship_date = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_expectd_rec_ship_date",
                                    label: "EXPECTED RECEIVED SHIP DATE FIELD ID"
                                });

                                var search_brand_listid = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_brand_listid",
                                    label: "BRAND LIST ID"
                                });
                            }

                            //set value to the fields.
                            ats_token.defaultValue = search_ats_token;
                            //ats_page_size.defaultValue = search_ats_page_size;
                            email_sender.defaultValue = search_email_sender;
                            ats_endpoint.defaultValue = search_ata_endpoint;
                            integrationid.defaultValue = search_integration_field_id;
                            itemcolorid.defaultValue = search_item_color_fieldid;
                            itemsizeid.defaultValue = search_item_size_fieldid;
                            itembrandid.defaultValue = search_item_brand_fieldid;
                            exptd_ship_dateid.defaultValue = search_expected_ship_date;
                            exptd_recvd_dateid.defaultValue = search_expectd_rec_ship_date;
                            brandlistid.defaultValue = search_brand_listid;


                            if (Edit != "TRUE") {
                                // Make the fields disabled.
                                ats_token.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                /*ats_page_size.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });*/
                                email_sender.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                ats_endpoint.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                integrationid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                itemcolorid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                itemsizeid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                itembrandid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                exptd_ship_dateid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                exptd_recvd_dateid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });
                                brandlistid.updateDisplayType({
                                    displayType: serverWidget.FieldDisplayType.DISABLED
                                });

                                form.addButton({
                                    id: 'edit',
                                    label: 'Edit',
                                    functionName: 'editBtnAction'
                                });
                                form.addButton({
                                    id: 'addlocation',
                                    label: 'Add Location',
                                    functionName: 'locationBtnAction'
                                });
                                form.addButton({
                                    id: 'addbrand',
                                    label: 'Add Brand',
                                    functionName: 'brandBtnAction'
                                });


                            } else {
                                log.debug('no results1');

                                form.addSubmitButton({
                                    id: 'save',
                                    label: 'Save'
                                });

                                form.addButton({
                                    id: 'cancel',
                                    label: 'Cancel',
                                    functionName: 'cancel'
                                });

                            }

                            // search to get client script internal id
                            var scriptSearchObj = search.create({
                                type: "script",
                                filters: [
                                    ["scriptid", "is", "customscript_jj_bpl2_cs_branscopesetup"]
                                ],
                                columns: [

                                    search.createColumn({ name: "scriptfile", label: "Script File" }),
                                    search.createColumn({
                                        name: "internalid",
                                        sort: search.Sort.ASC,
                                        label: "Internal ID"
                                    })
                                ]
                            });
                            var searchResultCount = scriptSearchObj.runPaged().count;
                            log.debug("scriptSearchObj result count", searchResultCount);

                            var searchResult_length = searchResults.length;

                            var searchResult = scriptSearchObj.run().getRange({
                                start: 0,
                                end: 50
                            });

                            for (var j = 0; j < searchResultCount; j++) {

                                var singleResult = searchResult[j];

                                var internalid = singleResult.getValue({
                                    name: "scriptfile",
                                    label: "Script File"
                                });
                            }

                            form.clientScriptFileId = internalid;

                        } catch (e) {
                            logme("@search2", getError(e));
                        }
                    } else {
                        log.debug('no results2');
                        form.addSubmitButton({
                            id: 'save',
                            label: 'Save'
                        });

                        form.addButton({
                            id: 'cancel',
                            label: 'Cancel',
                            functionName: 'cancel'
                        });
                    }

                    context.response.writePage(form);

                } else {
                    try {

                        var params = context.request.parameters
                        //get values from current form
                        var ats_token = params.custpage_brandscope_ats_token;
                        //var ats_page_size = params.custpage_brandscope_ats_page_size;
                        var ats_endpoint = params.custpage_brandscope_ats_endpoint;
                        var email_sender = params.custpage_brandscope_ats_email_sender;
                        var integrationid = params.custpage_brandscope_integrationid;
                        var itemcolorid = params.custpage_brandscope_itemcolorid;
                        var itemsizeid = params.custpage_brandscope_itemsizeid;
                        var itembrandid = params.custpage_brandscope_itembrandid;
                        var exptd_ship_dateid = params.custpage_brandscope_exptd_ship_dateid;
                        var exptd_recvd_dateid = params.custpage_brandscope_exptd_recvd_dateid;
                        var brandlistid = params.custpage_brandscope_brandlistid;

                        var customrecord479SearchObj = search.create({
                            type: "customrecord_jj_bpl2_cust_brandsetup",
                            filters: [],
                            columns: [
                                search.createColumn({
                                    name: "scriptid",
                                    sort: search.Sort.ASC,
                                    label: "Script ID"
                                }),
                                search.createColumn({ name: "custrecord_jj_bpl2_ats_token", label: "ATS TOKEN" }),
                                //search.createColumn({ name: "custrecord_jj_bpl2_ats_page_size", label: "ATS PAGE SIZE" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_email_sender", label: "EMAIL SENDER (EMPLOYEE)" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_ata_endpoint", label: "ATS ENDPOINT" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_integration_field_id", label: "INTEGRATION FIELD ID" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_item_color_fieldid", label: "ITEM COLOUR FIELD ID" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_item_size_fieldid", label: "ITEM SIZE FIELD ID" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_item_brand_fieldid", label: "ITEM BRAND FIELD ID" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_expected_ship_date", label: "EXPECTED SHIP DATE FIELD ID" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_expectd_rec_ship_date", label: "EXPECTED RECEIVED SHIP DATE FIELD ID" }),
                                search.createColumn({ name: "custrecord_jj_bpl2_brand_listid", label: "BRAND LIST ID" }),
                                search.createColumn({ name: "internalid", label: "Internal ID" })
                            ]
                        });
                        var searchResultCount = customrecord479SearchObj.runPaged().count;
                        //logme("customrecord479SearchObj result count", searchResultCount);
                        var searchResultCount = customrecord479SearchObj.runPaged().count;
                        var searchResults = customrecord479SearchObj.run().getRange({
                            start: 0,
                            end: 5
                        });

                        var searchResult_length = searchResults.length;

                        if (searchResult_length == 0) {
                            try {

                                var customRecord = record.create({
                                    type: 'customrecord_jj_bpl2_cust_brandsetup',
                                    isDynamic: true
                                });
                                //set ATS Token
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_ats_token',
                                    value: ats_token.toString().trim()
                                });
                                /*//set ATS page size
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_ats_page_size',
                                    value: ats_page_size
                                });*/
                                //set ATS endpoint
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_ata_endpoint',
                                    value: ats_endpoint.toString().trim()
                                });
                                //set Email Sender
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_email_sender',
                                    value: email_sender.toString().trim()
                                });
                                //set Integration ID
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_integration_field_id',
                                    value: integrationid.toString().trim()
                                });
                                //set Item color field ID
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_item_color_fieldid',
                                    value: itemcolorid.toString().trim()
                                });
                                //set Item size field ID
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_item_size_fieldid',
                                    value: itemsizeid.toString().trim()
                                });
                                //set Item brand Field ID
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_item_brand_fieldid',
                                    value: itembrandid.toString().trim()
                                });
                                //set Expected Ship date
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_expected_ship_date',
                                    value: exptd_ship_dateid.toString().trim()
                                });
                                //set Received ship date
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_expectd_rec_ship_date',
                                    value: exptd_recvd_dateid.toString().trim()
                                });
                                //set brand list id
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_brand_listid',
                                    value: brandlistid.toString().trim()
                                });

                                // saving record
                                var recordId = customRecord.save({
                                    enableSourcing: true,
                                    ignoreMandatoryFields: false
                                });

                                redirect.toSuitelet({
                                    scriptId: 'customscript_jj_bpl2_sl_brandscope_setup',
                                    deploymentId: 'customdeploy_jj_bpl2_id_setup'
                                });


                            } catch (e) {
                                logme("@first create", getError(e));
                            }
                        } else {

                            var searchResult = customrecord479SearchObj.run().getRange({
                                start: 0,
                                end: 50
                            });

                            for (var j = 0; j < searchResultCount; j++) {

                                var singleResult = searchResult[j];

                                var internalid = singleResult.getValue({
                                    name: "internalid",
                                    label: "Internal ID"
                                });
                            }

                            //create Brandscope record
                            var customRecord = record.load({
                                type: 'customrecord_jj_bpl2_cust_brandsetup',
                                id: internalid,
                                isDynamic: true
                            });
                            //set ATS Token
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_ats_token',
                                value: ats_token.toString().trim()
                            });
                            /*//set ATS page size
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_ats_page_size',
                                value: ats_page_size
                            });*/
                            //set ATS endpoint
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_ata_endpoint',
                                value: ats_endpoint.toString().trim()
                            });
                            //set Email Sender
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_email_sender',
                                value: email_sender.toString().trim()
                            });
                            //set Integration ID
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_integration_field_id',
                                value: integrationid.toString().trim()
                            });
                            //set Item color field ID
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_item_color_fieldid',
                                value: itemcolorid.toString().trim()
                            });
                            //set Item size field ID
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_item_size_fieldid',
                                value: itemsizeid.toString().trim()
                            });
                            //set Item brand Field ID
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_item_brand_fieldid',
                                value: itembrandid.toString().trim()
                            });
                            //set Expected Ship date
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_expected_ship_date',
                                value: exptd_ship_dateid.toString().trim()
                            });
                            //set Received ship date
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_expectd_rec_ship_date',
                                value: exptd_recvd_dateid.toString().trim()
                            });
                            //set brand list id
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_brand_listid',
                                value: brandlistid.toString().trim()
                            });

                            // saving record
                            var recordId = customRecord.save({
                                enableSourcing: true,
                                ignoreMandatoryFields: false
                            });

                            redirect.toSuitelet({
                                scriptId: 'customscript_jj_bpl2_sl_brandscope_setup',
                                deploymentId: 'customdeploy_jj_bpl2_id_setup'
                            });
                        }


                    } catch (e) {
                        logme('Error in Post Method', getError(e));
                    }
                }

            } catch (e) {
                logme('e@3', getError(e));
            }

        }

        return {
            onRequest: onRequest
        };


        // To update the location sublist in Brandscope setup   
        function locationsublistvalue() {
            var temObject = {};
            var object = {};
            var customrecord_jj_bpl2_brandscope_locationSearchObj = search.create({
                type: "customrecord_jj_bpl2_brandscope_location",
                filters: [],
                columns: [
                    search.createColumn({
                        name: "scriptid",
                        sort: search.Sort.ASC,
                        label: "Script ID"
                    }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brandscopelocation", label: "Brandscope" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_location", label: "Location" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_abbreviations", label: "Abbreviations" }),
                    search.createColumn({ name: "internalid", label: "Internal ID" })
                ]
            });
            var searchResultCount = customrecord_jj_bpl2_brandscope_locationSearchObj.runPaged().count;
            log.debug("customrecord_jj_bpl2_brandscope_locationSearchObj result count", searchResultCount);

            if (searchResultCount) {

                var searchResult = customrecord_jj_bpl2_brandscope_locationSearchObj.run().getRange({
                    start: 0,
                    end: 50
                });
                var locationarray = [],
                    locarray = [];

                for (var j = 0; j < searchResultCount; j++) {

                    var singleResult = searchResult[j];


                    var locationval = singleResult.getText({
                        name: "custrecord_jj_bpl2_location",
                        label: "Location"
                    });

                    if (object[locationval]) {

                    } else {
                        object[locationval] = ({

                            locationval: singleResult.getText({
                                name: "custrecord_jj_bpl2_location",
                                label: "Location"
                            }),
                            abbr_value: singleResult.getValue({
                                name: "custrecord_jj_bpl2_abbreviations",
                                label: "Abbreviations"
                            })

                        });


                    }
                }
                locationarray.push(object);

            }
            //logme("locationarraytest",locationarray);
            return locationarray;
        }



        function brandsublistvalue() {

            var temObject = {};
            var customrecord481SearchObj = search.create({
                type: "customrecord_jj_bpl2_custbrandid",
                filters: [],
                columns: [
                    search.createColumn({
                        name: "scriptid",
                        sort: search.Sort.ASC,
                        label: "Script ID"
                    }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brand_locationid", label: "Brandscope" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brand", label: "Brand" })
                ]
            });
            var searchResultCount = customrecord481SearchObj.runPaged().count;
            log.debug("customrecord481SearchObj result count", searchResultCount);

            if (searchResultCount) {

                var searchResult = customrecord481SearchObj.run().getRange({
                    start: 0,
                    end: 50
                });
                var brandarray = [],
                    locarray = [];

                for (var j = 0; j < searchResultCount; j++) {

                    var singleResult = searchResult[j];
                    var obj = {};

                    obj.brandlocationval = singleResult.getText({
                        name: "custrecord_jj_bpl2_brandlocation",
                        label: "Location"
                    });

                    obj.brand_value = singleResult.getText({
                        name: "custrecord_jj_bpl2_brand",
                        label: "Brand"
                    });

                    brandarray.push(obj);

                }
            }
            return brandarray;
        }


        /*******************************************************************************
         * return error
         * 
         * @param e
         * @returns
         */
        function getError(e) {
            var stErrMsg = '';
            if (e.getDetails != undefined) {
                stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
                    e.getStackTrace();
            } else {
                stErrMsg = '_' + e.toString();
            }
            return stErrMsg;
        }

        /*******************************************************************************
         * Log these data
         * 
         * @param title
         * @param details
         * @returns
         */
        function logme(title, details) {
            log.error({
                title: title,
                details: details
            });
        }

        //To check whether a value exists in parameter
        function checkForParameter(parameter, parameterName) {
            if (parameter != "" && parameter != null && parameter != undefined && parameter != "null" && parameter != "undefined" && parameter != " ") {
                return true;
            } else {
                if (parameterName)
                    log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
                return false;
            }
        }

        //To assign a default value if the it is empty
        function assignDefaultValue(value, defaultValue) {
            if (checkForParameter(value))
                return value;
            else
                return defaultValue;
        }

    });

Suitelet

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/**
 * Script Description
 *  Brandscope setup - Brandscope Location form
 */
/*******************************************************************************
 * Brandscope Pty Ltd
 * **************************************************************************
 * 
 * Date: 01/03/2019
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 * 
 * REVISION HISTORY
 * 
 * Revision 1 $ 01/03/2019 Maria: Create
 * 
 ******************************************************************************/
var BRANDSCOPE_ID;
define(['N/http', 'N/record', 'N/redirect', 'N/search', 'N/ui/serverWidget', 'N/redirect'],

    function(http, record, redirect, search, serverWidget, redirect) {

        /**
         * Definition of the Suitelet script trigger point.
         *
         * @param {Object} context
         * @param {ServerRequest} context.request - Encapsulation of the incoming request
         * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
         * @Since 2015.2
         */
        function onRequest(context) {

            try {

                var customrecord479SearchObj = search.create({
                    type: "customrecord_jj_bpl2_cust_brandsetup",
                    filters: [],
                    columns: [
                        search.createColumn({
                            name: "scriptid",
                            sort: search.Sort.ASC,
                            label: "Script ID"
                        }),
                        search.createColumn({ name: "custrecord_jj_bpl2_ats_token", label: "ATS TOKEN" }),                       
                        search.createColumn({ name: "internalid", label: "Internal ID" })
                    ]
                });
                var searchResultCount = customrecord479SearchObj.runPaged().count;
                //logme("customrecord479SearchObj result count", searchResultCount);
                var searchResultCount = customrecord479SearchObj.runPaged().count;
                var searchResults = customrecord479SearchObj.run().getRange({
                    start: 0,
                    end: 5
                });

                var searchResult_length = searchResults.length;

                var searchResult = customrecord479SearchObj.run().getRange({
                    start: 0,
                    end: 50
                });

                for (var j = 0; j < searchResultCount; j++) {

                    var singleResult = searchResult[j];

                    var internalid = singleResult.getValue({
                        name: "internalid",
                        label: "Internal ID"
                    });
                }

                BRANDSCOPE_ID = internalid;

                log.debug("context.request.method", context.request.method);
                var Edit = assignDefaultValue(context.request.parameters.Edit, 'FALSE');


                if (context.request.method === 'POST') {
                    /* var locationAbbrevations = [];*/
                    var locationAbbrevations = context.request.body;

                    var locationabbr = JSON.parse(locationAbbrevations);

                    if (locationabbr) {

                        LocAbbrevations(locationabbr);
                    }
                }

                //create suitelet form for location sublist.
                if (context.request.method === 'GET') {
                    var form = serverWidget.createForm({
                        title: 'Add Location'
                    });

                    var location_sublist = form.addSublist({
                        id: 'custpage_brandscope_location_sublist',
                        type: serverWidget.SublistType.INLINEEDITOR,
                        label: 'LOCATION'
                    });
                    var location = location_sublist.addField({
                        id: 'custpage_brandscope_location',
                        type: serverWidget.FieldType.SELECT,
                        label: 'LOCATION',
                        source: 'location'
                    });
                    location.isMandatory = true;

                    var location_abbr = location_sublist.addField({
                        id: 'custpage_brandscope_location_abbr',
                        type: serverWidget.FieldType.TEXT,
                        label: 'ABBREVIATIONS'
                    });
                    location_abbr.isMandatory = true;

                    //ADDING PROGRESS BAR

                    var fileSearchObj = search.create({
                       type: "file",
                       filters:
                       [
                          ["filetype","anyof","GIFIMAGE"], 
                          "AND", 
                          ["name","is","BPL-2 JJ loading-ani.gif"]
                       ],
                       columns:
                       [
                          search.createColumn({
                             name: "name",
                             sort: search.Sort.ASC,
                             label: "Name"
                          }),
                          search.createColumn({name: "folder", label: "Folder"}),
                          search.createColumn({name: "documentsize", label: "Size (KB)"}),
                          search.createColumn({name: "url", label: "URL"}),
                          search.createColumn({name: "created", label: "Date Created"}),
                          search.createColumn({name: "modified", label: "Last Modified"}),
                          search.createColumn({name: "filetype", label: "Type"})
                       ]
                    });
                    var searchResultCount = fileSearchObj.runPaged().count;
                    log.debug("fileSearchObj result count",searchResultCount);
                    var searchResults = fileSearchObj.run().getRange({
                        start: 0,
                        end: 5
                    });

                    var searchResult_length = searchResults.length;
                
                            for (var i = 0; i < searchResult_length; i++) {

                                var searchResult = searchResults[i];

                                var imageurl = searchResult.getValue({
                                    name: "url",
                                    label: "URL"
                                });
                            }


                    var progressBarField = form.addField({
                        id: 'custpage_progress_bar',
                        type: 'INLINEHTML',
                        label: 'Progress bar'
                    });

                    var loadingUrl = imageurl;

                    var html = "<div><img id='custpage_load_img' style='height:40px;top: 170px;left: 435px;position: absolute; display:none'  src='" + loadingUrl + "'/></div>";

                    progressBarField.defaultValue = html;
                    
                    var location_array = locationsublistvalue();


                    if (location_array) {

                        for (i = 0; i < location_array.length; i++) {
                            if (location_array[i].locationval) {
                                location_sublist.setSublistValue({
                                    id: 'custpage_brandscope_location',
                                    line: i,
                                    value: location_array[i].locationval
                                });
                            }
                            if (location_array[i].abbr_value) {
                                location_sublist.setSublistValue({
                                    id: 'custpage_brandscope_location_abbr',
                                    line: i,
                                    value: location_array[i].abbr_value
                                });
                            }
                        }
                    }

                    form.addButton({
                        id: 'locationsave',
                        label: 'Save',
                        functionName: 'locationsaveBtnAction'
                    });

                    form.addButton({
                        id: 'locationcancel',
                        label: 'Cancel',
                        functionName: 'locationcancelBtnAction'
                    });

                    //search to get client script internal id
                       var scriptSearchObj = search.create({
                       type: "script",
                       filters:
                       [
                          ["scriptid","is","customscript_jj_bpl2_cs_branscopesetup"]
                       ],
                       columns:
                       [
                          
                          search.createColumn({name: "scriptfile", label: "Script File"}),
                          search.createColumn({
                             name: "internalid",
                             sort: search.Sort.ASC,
                             label: "Internal ID"
                          })
                       ]
                    });
                    var searchResultCount = scriptSearchObj.runPaged().count;
                    log.debug("scriptSearchObj result count",searchResultCount);
                    
                    var searchResult_length = searchResults.length;

                    var searchResult = scriptSearchObj.run().getRange({
                        start: 0,
                        end: 50
                    });

                    for (var j = 0; j < searchResultCount; j++) {

                        var singleResult = searchResult[j];

                        var internalid = singleResult.getValue({
                            name: "scriptfile",
                            label: "Script File"
                        });
                    }
                    form.clientScriptFileId = internalid;
                    context.response.writePage(form);
                }

            } catch (e) {
                logme('e@3', getError(e));
            }

        }

        return {
            onRequest: onRequest
        };


        // To update the location sublist in Brandscope setup	
        function locationsublistvalue() {
            var temObject = {};
            var customrecord_jj_bpl2_brandscope_locationSearchObj = search.create({
                type: "customrecord_jj_bpl2_brandscope_location",
                filters: [],
                columns: [
                    search.createColumn({
                        name: "scriptid",
                        sort: search.Sort.ASC,
                        label: "Script ID"
                    }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brandscopelocation", label: "Brandscope" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_location", label: "Location" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_abbreviations", label: "Abbreviations" }),
                    search.createColumn({ name: "internalid", label: "Internal ID" })
                ]
            });
            var searchResultCount = customrecord_jj_bpl2_brandscope_locationSearchObj.runPaged().count;
            log.debug("customrecord_jj_bpl2_brandscope_locationSearchObj result count", searchResultCount);

            if (searchResultCount) {

                var searchResult = customrecord_jj_bpl2_brandscope_locationSearchObj.run().getRange({
                    start: 0,
                    end: 50
                });
                var locationarray = [],
                    locarray = [];

                for (var j = 0; j < searchResultCount; j++) {

                    var singleResult = searchResult[j];
                    var obj = {};

                    obj.locationval = singleResult.getValue({
                        name: "custrecord_jj_bpl2_location",
                        label: "Location"
                    });

                    obj.abbr_value = singleResult.getValue({
                        name: "custrecord_jj_bpl2_abbreviations",
                        label: "Abbreviations"
                    });

                    locationarray.push(obj);

                }

            }
            return locationarray;
        }


        function LocAbbrevations(currentAbbrevations) {

            try {
                var customrecord_jj_bpl2_brandscope_locationSearchObj = search.create({
                    type: "customrecord_jj_bpl2_brandscope_location",
                    filters: [],
                    columns: [
                        //search.createColumn({ name: "scriptid", label: "Script ID" }),
                        search.createColumn({ name: "custrecord_jj_bpl2_brandscopelocation", label: "Brandscope" }),
                        search.createColumn({ name: "custrecord_jj_bpl2_location", label: "Location" }),
                        search.createColumn({ name: "custrecord_jj_bpl2_abbreviations", label: "Abbreviations" }),
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        })
                    ]
                });
                var searchResultCount = customrecord_jj_bpl2_brandscope_locationSearchObj.runPaged().count;
                log.debug("customrecord_jj_bpl2_brandscope_locationSearchObj resulttest count", searchResultCount);
                var processedAbbrevations = {};

                customrecord_jj_bpl2_brandscope_locationSearchObj.run().each(function(result) {


                    if (currentAbbrevations[result.getValue({ name: "custrecord_jj_bpl2_location", label: "Location" })]) {
                        processedAbbrevations[result.getValue({ name: "custrecord_jj_bpl2_location", label: "Location" })] = true;
                        if (currentAbbrevations[result.getValue({ name: "custrecord_jj_bpl2_location", label: "Location" })] != result.getValue({ name: "custrecord_jj_bpl2_abbreviations", label: "Abbreviations" })) {
                            /*if (currentAbbrevations[result.getValue({ name: "custrecord_jj_bpl2_location", label: "Location" })] == result.getValue({ name: "custrecord_jj_bpl2_abbreviations", label: "Abbreviations" })) {*/
                            //update
                            var otherId = record.submitFields({
                                type: 'customrecord_jj_bpl2_brandscope_location',
                                id: result.getValue({ name: "internalid", label: "Internal ID" }),
                                values: {
                                    'custrecord_jj_bpl2_location': result.getValue({ name: "custrecord_jj_bpl2_location", label: "Location" }),
                                    'custrecord_jj_bpl2_abbreviations': currentAbbrevations[result.getValue({ name: "custrecord_jj_bpl2_location", label: "Location" })]
                                }
                            });
                        /*}*/
                        }

                    } else {
                        //delete
                        record.delete({
                            type: 'customrecord_jj_bpl2_brandscope_location',
                            id: result.getValue({ name: "internalid", label: "Internal ID" })
                        });
                    }

                    return true;
                });
                for (var key in currentAbbrevations) {
                    if (!processedAbbrevations[key]) {
                        //create

                        var customRecord = record.create({
                            type: 'customrecord_jj_bpl2_brandscope_location',
                            isDynamic: true
                        });
                        customRecord.setValue({
                            fieldId: 'custrecord_jj_bpl2_brandscopelocation',
                            value: BRANDSCOPE_ID
                        });
                        customRecord.setValue({
                            fieldId: 'custrecord_jj_bpl2_location',
                            value: key
                        });
                        customRecord.setValue({
                            fieldId: 'custrecord_jj_bpl2_abbreviations',
                            value: currentAbbrevations[key]
                        });
                        // saving record
                        var recordId = customRecord.save({
                            enableSourcing: true,
                            ignoreMandatoryFields: true
                        });

                    }
                }

            } catch (e) {
                logme('e@currentAbbrevations', getError(e));
            }


        }
        /*******************************************************************************
         * return error
         * 
         * @param e
         * @returns
         */
        function getError(e) {
            var stErrMsg = '';
            if (e.getDetails != undefined) {
                stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
                    e.getStackTrace();
            } else {
                stErrMsg = '_' + e.toString();
            }
            return stErrMsg;
        }

        /*******************************************************************************
         * Log these data
         * 
         * @param title
         * @param details
         * @returns
         */
        function logme(title, details) {
            log.error({
                title: title,
                details: details
            });
        }

        //To check whether a value exists in parameter
        function checkForParameter(parameter, parameterName) {
            if (parameter != "" && parameter != null && parameter != undefined && parameter != "null" && parameter != "undefined" && parameter != " ") {
                return true;
            } else {
                if (parameterName)
                    log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
                return false;
            }
        }

        //To assign a default value if the it is empty
        function assignDefaultValue(value, defaultValue) {
            if (checkForParameter(value))
                return value;
            else
                return defaultValue;
        }

    });

Suitelet:

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/**
 * Script Description
 *  Brandscope setup - Brandscope Brand form
 */
/*******************************************************************************
 * Brandscope Pty Ltd
 * **************************************************************************
 * 
 * Date: 01/03/2019
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 * 
 * REVISION HISTORY
 * 
 * Revision 1 $ 01/03/2019 Maria: Create
 * 
 ******************************************************************************/
var BRANDSCOPE_ID;
define(['N/http', 'N/record', 'N/redirect', 'N/search', 'N/ui/serverWidget', 'N/redirect'],

    function(http, record, redirect, search, serverWidget, redirect) {

        /**
         * Definition of the Suitelet script trigger point.
         *
         * @param {Object} context
         * @param {ServerRequest} context.request - Encapsulation of the incoming request
         * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
         * @Since 2015.2
         */
        function onRequest(context) {

            try {

                var customrecord479SearchObj = search.create({
                    type: "customrecord_jj_bpl2_cust_brandsetup",
                    filters: [],
                    columns: [
                        search.createColumn({
                            name: "scriptid",
                            sort: search.Sort.ASC,
                            label: "Script ID"
                        }),
                        search.createColumn({ name: "custrecord_jj_bpl2_ats_token", label: "ATS TOKEN" }),      
                        search.createColumn({ name: "internalid", label: "Internal ID" })
                    ]
                });
                var searchResultCount = customrecord479SearchObj.runPaged().count;
                //logme("customrecord479SearchObj result count", searchResultCount);
                //var searchResultCount = customrecord479SearchObj.runPaged().count;
                var searchResults = customrecord479SearchObj.run().getRange({
                    start: 0,
                    end: 5
                });

                var searchResult_length = searchResults.length;

                var searchResult = customrecord479SearchObj.run().getRange({
                    start: 0,
                    end: 50
                });

                for (var j = 0; j < searchResultCount; j++) {

                    var singleResult = searchResult[j];

                    var internalid = singleResult.getValue({
                        name: "internalid",
                        label: "Internal ID"
                    });
                }

                BRANDSCOPE_ID = internalid;

                var Brand = assignDefaultValue(context.request.parameters.Brand, 'FALSE');


                if (context.request.method === 'POST') {
                    /*var locationAbbrevations = {};*/
                    var locbrand = context.request.body;
                    
                    var brandlocation = JSON.parse(locbrand);                 

                    if (brandlocation) {

                        LocationBrand(brandlocation);
                    }
                }

                //create suitelet form for location sublist.
                if (context.request.method === 'GET') {
                    var form = serverWidget.createForm({
                        title: 'Add Brand'
                    });

                    var brand_sublist = form.addSublist({
                        id: 'custpage_brandscope_brand_sublist',
                        type: serverWidget.SublistType.INLINEEDITOR,
                        label: 'BRAND'
                    });
                    var location_brand = brand_sublist.addField({
                        id: 'custpage_brandscope_location_brand',
                        type: serverWidget.FieldType.SELECT,
                        label: 'LOCATION',
                        source: 'location'
                    });
                    location_brand.isMandatory = true;

                     var customrecord479SearchObj = search.create({
                        type: "customrecord_jj_bpl2_cust_brandsetup",
                        filters: [],
                        columns: [
                            search.createColumn({
                                name: "scriptid",
                                sort: search.Sort.ASC,
                                label: "Script ID"
                            }),                            
                            search.createColumn({name: "custrecord_jj_bpl2_brand_listid", label: "BRAND LIST ID"}),
                            search.createColumn({ name: "internalid", label: "Internal ID" })
                        ]
                    });
                    var searchResultCount = customrecord479SearchObj.runPaged().count;
                    //logme("customrecord479SearchObj result count", searchResultCount);
                    var searchResultCount = customrecord479SearchObj.runPaged().count;
                    var searchResults = customrecord479SearchObj.run().getRange({
                        start: 0,
                        end: 5
                    });

                    var searchResult_length = searchResults.length;
                
                            for (var i = 0; i < searchResult_length; i++) {

                                var searchResult = searchResults[i];

                                var brandlist = searchResult.getValue({
                                    name: "custrecord_jj_bpl2_brand_listid",
                                    label: "BRAND LIST ID"
                                })
                            }


                    var brand = brand_sublist.addField({
                        id: 'custpage_brandscope_brand',
                        type: serverWidget.FieldType.SELECT,
                        label: 'BRAND',
                        source: brandlist
                    });
                    brand.isMandatory = true;

                    //ADDING PROGRESS BAR 

                    var fileSearchObj = search.create({
                       type: "file",
                       filters:
                       [
                          ["filetype","anyof","GIFIMAGE"], 
                          "AND", 
                          ["name","is","BPL-2 JJ loading-ani.gif"]
                       ],
                       columns:
                       [
                          search.createColumn({
                             name: "name",
                             sort: search.Sort.ASC,
                             label: "Name"
                          }),
                          search.createColumn({name: "folder", label: "Folder"}),
                          search.createColumn({name: "documentsize", label: "Size (KB)"}),
                          search.createColumn({name: "url", label: "URL"}),
                          search.createColumn({name: "created", label: "Date Created"}),
                          search.createColumn({name: "modified", label: "Last Modified"}),
                          search.createColumn({name: "filetype", label: "Type"})
                       ]
                    });
                    var searchResultCount = fileSearchObj.runPaged().count;
                    log.debug("fileSearchObj result count",searchResultCount);
                    var searchResults = fileSearchObj.run().getRange({
                        start: 0,
                        end: 5
                    });

                    var searchResult_length = searchResults.length;
                
                            for (var i = 0; i < searchResult_length; i++) {

                                var searchResult = searchResults[i];

                                var imageurl = searchResult.getValue({
                                    name: "url",
                                    label: "URL"
                                });
                            }

                    var progressBarField = form.addField({
                        id: 'custpage_progress_bar',
                        type: 'INLINEHTML',
                        label: 'Progress bar'
                    });

                    var loadingUrl = imageurl;

                    var html = "<div><img id='custpage_load_img' style='height:40px;top: 170px;left: 435px;position: absolute; display:none'  src='" + loadingUrl + "'/></div>";

                    progressBarField.defaultValue = html;
                    log.debug('html', html);


                    var brand_array = brandsublistvalue();

                    if (brand_array) {

                        for (j = 0; j < brand_array.length; j++) {

                            if (brand_array[j].brandlocationval) {
                                brand_sublist.setSublistValue({
                                    id: 'custpage_brandscope_location_brand',
                                    line: j,
                                    value: brand_array[j].brandlocationval
                                });
                            }
                            if (brand_array[j].brand_value) {
                                brand_sublist.setSublistValue({
                                    id: 'custpage_brandscope_brand',
                                    line: j,
                                    value: brand_array[j].brand_value
                                });
                            }
                        }
                    }

                    form.addButton({
                        id: 'brandsave',
                        label: 'Save',
                        functionName: 'brandsaveBtnAction'
                    });

                    form.addButton({
                        id: 'brandcancel',
                        label: 'Cancel',
                        functionName: 'brandcancelBtnAction'
                    });

                    //search to get client script internal id
                    var scriptSearchObj = search.create({
                       type: "script",
                       filters:
                       [
                          ["scriptid","is","customscript_jj_bpl2_cs_branscopesetup"]
                       ],
                       columns:
                       [
                          
                          search.createColumn({name: "scriptfile", label: "Script File"}),
                          search.createColumn({
                             name: "internalid",
                             sort: search.Sort.ASC,
                             label: "Internal ID"
                          })
                       ]
                    });
                    var searchResultCount = scriptSearchObj.runPaged().count;
                    log.debug("scriptSearchObj result count",searchResultCount);
                    
                    var searchResult_length = searchResults.length;

                    var searchResult = scriptSearchObj.run().getRange({
                        start: 0,
                        end: 50
                    });

                    for (var j = 0; j < searchResultCount; j++) {

                        var singleResult = searchResult[j];

                        var internalid = singleResult.getValue({
                            name: "scriptfile",
                            label: "Script File"
                        });
                    }
                    

                    form.clientScriptFileId = internalid;
                    context.response.writePage(form);
                }

            } catch (e) {
                logme('e@3', getError(e));
            }

        }

        return {
            onRequest: onRequest
        };

        function brandsublistvalue() {

            var temObject = {};
            var customrecord481SearchObj = search.create({
                type: "customrecord_jj_bpl2_custbrandid",
                filters: [],
                columns: [
                    search.createColumn({
                        name: "scriptid",
                        sort: search.Sort.ASC,
                        label: "Script ID"
                    }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brand_locationid", label: "Brandscope" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" }),
                    search.createColumn({ name: "custrecord_jj_bpl2_brand", label: "Brand" })
                ]
            });
            var searchResultCount = customrecord481SearchObj.runPaged().count;
            log.debug("customrecord481SearchObj result count", searchResultCount);

            if (searchResultCount) {

                var searchResult = customrecord481SearchObj.run().getRange({
                    start: 0,
                    end: 50
                });
                var brandarray = [],
                    locarray = [];

                for (var j = 0; j < searchResultCount; j++) {

                    var singleResult = searchResult[j];
                    var obj = {};

                    obj.brandlocationval = singleResult.getValue({
                        name: "custrecord_jj_bpl2_brandlocation",
                        label: "Location"
                    });

                    obj.brand_value = singleResult.getValue({
                        name: "custrecord_jj_bpl2_brand",
                        label: "Brand"
                    });

                    brandarray.push(obj);

                }

            }
            return brandarray;
        }


        function LocationBrand(currentlocation) {

            try {

                var customrecord481SearchObj = search.create({
                    type: "customrecord_jj_bpl2_custbrandid",
                    filters: [],
                    columns: [
                        search.createColumn({ name: "custrecord_jj_bpl2_brand_locationid", label: "Brandscope" }),
                        search.createColumn({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" }),
                        search.createColumn({ name: "custrecord_jj_bpl2_brand", label: "Brand" }),
                        search.createColumn({
                            name: "internalid",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        })
                    ]
                });
                var searchResultCount = customrecord481SearchObj.runPaged().count;
                log.debug("customrecord481SearchObj result count", searchResultCount);

                var processedbrand = {};
                customrecord481SearchObj.run().each(function(result) {

                    //location check only
                    if (currentlocation[result.getValue({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" })]) {
                        //location and brand check
                        if (currentlocation[result.getValue({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" })][{ name: "custrecord_jj_bpl2_brand", label: "Brand" }]) {
                            if (!processedbrand[result.getValue({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" })])
                                processedbrand[result.getValue({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" })] = {};
                            processedbrand[result.getValue({ name: "custrecord_jj_bpl2_brandlocation", label: "Location" })][{ name: "custrecord_jj_bpl2_brand", label: "Brand" }] = true;
                        } else {
                            //delete
                            record.delete({
                                type: 'customrecord_jj_bpl2_custbrandid',
                                id: result.getValue({ name: "internalid", label: "Internal ID" })
                            });
                        }

                    } else {
                        //delete
                        record.delete({
                            type: 'customrecord_jj_bpl2_custbrandid',
                            id: result.getValue({ name: "internalid", label: "Internal ID" })
                        });
                    }

                    return true;
                });

                for (var location in currentlocation) {
                    if (processedbrand[location]) {
                        for (var brand in currentlocation[location]) {
                            if (!processedbrand[location][brand]) {
                                var customRecord = record.create({
                                    type: 'customrecord_jj_bpl2_custbrandid',
                                    isDynamic: true
                                });
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_brand_locationid',
                                    value: BRANDSCOPE_ID
                                });
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_brandlocation',
                                    value: location
                                });
                                customRecord.setValue({
                                    fieldId: 'custrecord_jj_bpl2_brand',
                                    value: brand
                                });
                                // saving record
                                var recordId = customRecord.save({
                                    enableSourcing: true,
                                    ignoreMandatoryFields: true
                                });
                            }
                        }

                    } else {
                        for (var brand in currentlocation[location]) {
                            var customRecord = record.create({
                                type: 'customrecord_jj_bpl2_custbrandid',
                                isDynamic: true
                            });
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_brand_locationid',
                                value: BRANDSCOPE_ID
                            });
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_brandlocation',
                                value: location
                            });
                            customRecord.setValue({
                                fieldId: 'custrecord_jj_bpl2_brand',
                                value: brand
                            });
                            // saving record
                            var recordId = customRecord.save({
                                enableSourcing: true,
                                ignoreMandatoryFields: true
                            });
                        }
                    }
                }

            } catch (e) {
                logme('e@LocationBrand', getError(e));
            }

        }



        /*******************************************************************************
         * return error
         * 
         * @param e
         * @returns
         */
        function getError(e) {
            var stErrMsg = '';
            if (e.getDetails != undefined) {
                stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
                    e.getStackTrace();
            } else {
                stErrMsg = '_' + e.toString();
            }
            return stErrMsg;
        }

        /*******************************************************************************
         * Log these data
         * 
         * @param title
         * @param details
         * @returns
         */
        function logme(title, details) {
            log.error({
                title: title,
                details: details
            });
        }

        //To check whether a value exists in parameter
        function checkForParameter(parameter, parameterName) {
            if (parameter != "" && parameter != null && parameter != undefined && parameter != "null" && parameter != "undefined" && parameter != " ") {
                return true;
            } else {
                if (parameterName)
                    log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
                return false;
            }
        }

        //To assign a default value if the it is empty
        function assignDefaultValue(value, defaultValue) {
            if (checkForParameter(value))
                return value;
            else
                return defaultValue;
        }

    });

Leave a comment

Your email address will not be published. Required fields are marked *