We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

Confusion between Insert and update in Business rule

Abhijit Das7
Tera Expert

Hi Everyone, 

 

I have before business rule with insert and update checkbox as true. and this BR is for custom table which is for Supply chain order table to order parts for agents from mobile.  Currently the condition on filter for BR is:

StreetchangesOR
citychangesOR
statechangesOR
postal codechangesOR

 Current Script: current script is for whenever any changes happen to street, city, state, postal code.Current logic is ofcourse needed for whenever updates happen but want to add logic for insert also:

(function executeRule(current, previous /*null when async*/ ) {

    gs.log('BR called');
	
	var TSR = current.u_user;
    var XeroxUtils = new XeroxLoqateIntegrationUtils();
    var error = 'Enter a valid address';

    var cmnGR = new GlideRecord('cmn_location');

    cmnGR.addQuery('street', current.getValue('u_street'));
    cmnGR.addQuery('country', current.getValue('u_country'));
    cmnGR.addQuery('state', current.getValue('u_state_province'));

    cmnGR.addQuery('zip', current.getValue('u_postal_code'));
    var city;
    cmnGR.query();
    while (cmnGR.next()) {
        city = cmnGR.getValue('city');
    }


    var data = {
        "STREET": current.getValue('u_street'),
        "COUNTRY": current.getValue('u_country'),
        "STATE": current.getValue('u_state_province'),
        "CITY": (current.getValue('u_city') ? current.getValue('u_city') : city),
        "POSTALCODE": current.getValue('u_postal_code')
    };

    //gs.info('IK: Data object: ' + JSON.stringify(data));

    // Location validation
    //var responseArray = XeroxUtils.getLocationfromLoqateAPI(data, true);
    var locationID = XeroxUtils.getLocation(data, true, "supply_chain_order");
    //gs.info('IK: Location ID: ' +locationID);
    if (!gs.nil(locationID)) {
        current.location = locationID;
        current.u_location_address = locationID;
        var location = new GlideRecord("cmn_location");
        var stkRoom = new GlideRecord("alm_stockroom");
        if (gs.hasRole('wm_ext_agent')) { //contractors using a diffrent stockroom type 
            stkRoom.addQuery("assignment_group", current.assignment_group);
        } else {
            stkRoom.addQuery("type", "e2aa2b3f3763100044e0bfc8bcbe5dde");
            stkRoom.addQuery("manager", TSR);
        }
        stkRoom.query();
        // Assign value of service budget center
        if (stkRoom.next()) {
            var service_budget_center = stkRoom.u_service_budget_center;
            location.get(locationID);
            location.u_service_budget_center = stkRoom.u_service_budget_center;
            //location.u_service_budget_center_stockroom = stkRoom.sys_id + '';
            if (gs.hasRole('wm_ext_agent') && current.u_new_location_name != '') {
                location.name = current.u_new_location_name;
                location.managed_by_group = current.assignment_group;
            }
        }
        location.update();

    } else {
        gs.addErrorMessage('Please select a valid Location or enter a new location using Street, City, Country, Postal code');
        current.setAbortAction(true);

        try {
            action.setRedirectURL(current);
        } catch (error) {
            gs.log("IK: aborting location update in BR 'XRX Validate Location using Loqate'");
        }



    }



})(current, previous);



Now we want to make changes to this BR whenever new part is ordered from mobile, then it should check following conditions, if either of the conditions meet then we don't see error message:
conditions:
1. Ship to WOT location is true (Ship to WOT location is toggle button on mobile screen which is UI parameter which linked to data parameter (wot_location)) OR
2. A saved address is selected from the location dropdown (u_location_address) OR

3. A new address has been entered and is fully populated (all required fields are filled)

 

If one of the conditions is not met, display the error message" Please provide a complete address for shipping."

If the condition is met, then store the Supply Chain Order Record.

Note: These fields should be required if "Ship to WOT" is false and Location dropdown is null, along with existing required fills.

STREET, CITY, STATE, POSTAL_CODE, COUNTRY
How can I make changes to my existing BR to accommodate new enhancement. I am bit confused

Thanks in advance

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron

@Abhijit Das7 

use this -> determine insert/update operation using current.operation() and then handle the logic

(function executeRule(current, previous /* null when async */) {

    gs.log('BR called');

    var isInsert = current.operation() == 'insert';
    var isUpdate = current.operation() == 'update';

    var shipToWOT = current.getValue('wot_location') == 'true' || current.getValue('wot_location') == '1';
    var savedLocation = !gs.nil(current.getValue('u_location_address'));

    var street = current.getValue('u_street');
    var cityField = current.getValue('u_city');
    var state = current.getValue('u_state_province');
    var postalCode = current.getValue('u_postal_code');
    var country = current.getValue('u_country');

    var manualAddressComplete =
        !gs.nil(street) &&
        !gs.nil(cityField) &&
        !gs.nil(state) &&
        !gs.nil(postalCode) &&
        !gs.nil(country);

    if (isInsert) {
        if (!(shipToWOT || savedLocation || manualAddressComplete)) {
            gs.addErrorMessage('Please provide a complete address for shipping.');
            current.setAbortAction(true);
            return;
        }

        if (shipToWOT || savedLocation) {
            return;
        }
    }

    if (isUpdate) {
        var addressChanged =
            current.u_street.changes() ||
            current.u_city.changes() ||
            current.u_state_province.changes() ||
            current.u_postal_code.changes() ||
            current.u_country.changes() ||
            current.u_location_address.changes() ||
            current.wot_location.changes();

        if (!addressChanged) {
            return;
        }

        if (shipToWOT || savedLocation) {
            return;
        }

        if (!manualAddressComplete) {
            gs.addErrorMessage('Please provide a complete address for shipping.');
            current.setAbortAction(true);
            return;
        }
    }

    var TSR = current.u_user;
    var XeroxUtils = new XeroxLoqateIntegrationUtils();

    var cmnGR = new GlideRecord('cmn_location');
    cmnGR.addQuery('street', street);
    cmnGR.addQuery('country', country);
    cmnGR.addQuery('state', state);
    cmnGR.addQuery('zip', postalCode);

    var cityFromLocation = '';
    cmnGR.query();
    while (cmnGR.next()) {
        cityFromLocation = cmnGR.getValue('city');
    }

    var data = {
        "STREET": street,
        "COUNTRY": country,
        "STATE": state,
        "CITY": cityField || cityFromLocation,
        "POSTALCODE": postalCode
    };

    var locationID = XeroxUtils.getLocation(data, true, "supply_chain_order");

    if (!gs.nil(locationID)) {
        current.location = locationID;
        current.u_location_address = locationID;

        var location = new GlideRecord("cmn_location");
        var stkRoom = new GlideRecord("alm_stockroom");

        if (gs.hasRole('wm_ext_agent')) {
            stkRoom.addQuery("assignment_group", current.assignment_group);
        } else {
            stkRoom.addQuery("type", "e2aa2b3f3763100044e0bfc8bcbe5dde");
            stkRoom.addQuery("manager", TSR);
        }

        stkRoom.query();

        if (stkRoom.next()) {
            location.get(locationID);
            location.u_service_budget_center = stkRoom.u_service_budget_center;

            if (gs.hasRole('wm_ext_agent') && current.u_new_location_name != '') {
                location.name = current.u_new_location_name;
                location.managed_by_group = current.assignment_group;
            }

            location.update();
        }

    } else {
        gs.addErrorMessage('Please provide a complete address for shipping.');
        current.setAbortAction(true);

        try {
            action.setRedirectURL(current);
        } catch (e) {
            gs.log("aborting location update in BR");
        }
    }

})(current, previous);

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

View solution in original post

2 REPLIES 2

Rafael Batistot
Kilo Patron

Hi @Abhijit Das7 

 

In your Before Insert / Before Update Business Rule:

  1. Remove all changes conditions from the filter
    Let the script decide when to run.
  2. Run validation only when
    • Record is being inserted OR
    • Address fields changed on update
  3. Allow save if ANY condition is true
    • wot_location == true
    • u_location_address is not empty
    • All address fields are filled
  4. Block save only when ALL are false
    • Ship to WOT = false
    • Location dropdown = empty
    • Address incomplete
  5. If blocked
    • Show error: “Please provide a complete address for shipping.”
    • current.setAbortAction(true)

Minimal decision logic

 

var shouldValidate = current.operation() === 'insert' ||
current.u_street.changes() ||
current.u_city.changes() ||
current.u_state_province.changes() ||
current.u_postal_code.changes() ||
current.u_country.changes()

var allowed =
current.wot_location == 'true' ||
!gs.nil(current.u_location_address) ||
(current.u_street && current.u_city && current.u_state_province &&
current.u_postal_code && current.u_country)

!shouldValidate || allowed || (
gs.addErrorMessage('Please provide a complete address for shipping.'),
current.setAbortAction(true)
)

 

If this response was helpful, please mark it as Helpful and, if applicable, as Correct.
This helps other users find accurate and useful information more easily

Ankur Bawiskar
Tera Patron

@Abhijit Das7 

use this -> determine insert/update operation using current.operation() and then handle the logic

(function executeRule(current, previous /* null when async */) {

    gs.log('BR called');

    var isInsert = current.operation() == 'insert';
    var isUpdate = current.operation() == 'update';

    var shipToWOT = current.getValue('wot_location') == 'true' || current.getValue('wot_location') == '1';
    var savedLocation = !gs.nil(current.getValue('u_location_address'));

    var street = current.getValue('u_street');
    var cityField = current.getValue('u_city');
    var state = current.getValue('u_state_province');
    var postalCode = current.getValue('u_postal_code');
    var country = current.getValue('u_country');

    var manualAddressComplete =
        !gs.nil(street) &&
        !gs.nil(cityField) &&
        !gs.nil(state) &&
        !gs.nil(postalCode) &&
        !gs.nil(country);

    if (isInsert) {
        if (!(shipToWOT || savedLocation || manualAddressComplete)) {
            gs.addErrorMessage('Please provide a complete address for shipping.');
            current.setAbortAction(true);
            return;
        }

        if (shipToWOT || savedLocation) {
            return;
        }
    }

    if (isUpdate) {
        var addressChanged =
            current.u_street.changes() ||
            current.u_city.changes() ||
            current.u_state_province.changes() ||
            current.u_postal_code.changes() ||
            current.u_country.changes() ||
            current.u_location_address.changes() ||
            current.wot_location.changes();

        if (!addressChanged) {
            return;
        }

        if (shipToWOT || savedLocation) {
            return;
        }

        if (!manualAddressComplete) {
            gs.addErrorMessage('Please provide a complete address for shipping.');
            current.setAbortAction(true);
            return;
        }
    }

    var TSR = current.u_user;
    var XeroxUtils = new XeroxLoqateIntegrationUtils();

    var cmnGR = new GlideRecord('cmn_location');
    cmnGR.addQuery('street', street);
    cmnGR.addQuery('country', country);
    cmnGR.addQuery('state', state);
    cmnGR.addQuery('zip', postalCode);

    var cityFromLocation = '';
    cmnGR.query();
    while (cmnGR.next()) {
        cityFromLocation = cmnGR.getValue('city');
    }

    var data = {
        "STREET": street,
        "COUNTRY": country,
        "STATE": state,
        "CITY": cityField || cityFromLocation,
        "POSTALCODE": postalCode
    };

    var locationID = XeroxUtils.getLocation(data, true, "supply_chain_order");

    if (!gs.nil(locationID)) {
        current.location = locationID;
        current.u_location_address = locationID;

        var location = new GlideRecord("cmn_location");
        var stkRoom = new GlideRecord("alm_stockroom");

        if (gs.hasRole('wm_ext_agent')) {
            stkRoom.addQuery("assignment_group", current.assignment_group);
        } else {
            stkRoom.addQuery("type", "e2aa2b3f3763100044e0bfc8bcbe5dde");
            stkRoom.addQuery("manager", TSR);
        }

        stkRoom.query();

        if (stkRoom.next()) {
            location.get(locationID);
            location.u_service_budget_center = stkRoom.u_service_budget_center;

            if (gs.hasRole('wm_ext_agent') && current.u_new_location_name != '') {
                location.name = current.u_new_location_name;
                location.managed_by_group = current.assignment_group;
            }

            location.update();
        }

    } else {
        gs.addErrorMessage('Please provide a complete address for shipping.');
        current.setAbortAction(true);

        try {
            action.setRedirectURL(current);
        } catch (e) {
            gs.log("aborting location update in BR");
        }
    }

})(current, previous);

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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