Add Catalog Item to existing Request (with CartJS API)
Import
·
Jan 20, 2022
·
article
I wasn't really happy with the Solutions I have found on the community for this issue.
With the old way of doing this (GlideappCalculationHelper.addItemToExistingRequest) you have to populate the variables manually after the requested item has been inserted. So here is a solution to add a catalog item to an existing requested item by using the CartJS API.
Script Include
var addCatalogItemToRequest = function (requestSysId, catItemMap, startFlow) {
var tempCartName = "temp_" + gs.generateGUID();
var tempCart = new sn_sc.CartJS(tempCartName);
var cartItem = tempCart.addToCart(catItemMap).items[0];
var cartItemHint = "<hints><entry key='sysparm_processing_hint' value='" +
"setfield:request=" + requestSysId + "'/></hints>";
var grCartItem = new GlideRecord("sc_cart_item");
if (grCartItem.get(cartItem.cart_item_id)) {
grCartItem.setValue("hints", cartItemHint);
grCartItem.update();
}
//a business rule on sc_request will abort insert with these special_instructions
tempCart.submitOrder({
'special_instructions': '[__ABORT_INSERT_ACTION__]'
});
var getVars = function (grReqItem) {
var vars = {};
for (var n in grReqItem.variables) {
vars[n] = grReqItem.variables[n];
}
return vars;
};
var grReqItem = new GlideRecord("sc_req_item");
grReqItem.addEncodedQuery("request=" + requestSysId);
grReqItem.orderByDesc("sys_created_on");
grReqItem.setLimit(1);
grReqItem.query();
if (grReqItem.next()) {
if (startFlow) {
//as long as the OOTB business rules "Start Workflow" and "Start FlowDesigner Flow"
//aren't modified setting the stage to "request_approved" should start the (work)flow
grReqItem.stage = "request_approved";
grReqItem.update();
}
return grReqItem;
}
};
var requestId = 'd1eab3138741cd141820ed309bbb35b6'; //SysID of existing request
addCatalogItemToRequest(requestId, {
'sysparm_id': 'd6ea58701b1c41105ff0c036464bcb73', //SysID of catalog item
'sysparm_quantity': '1',
'variables': { //variables of catalog item
'type': 'Systemcopy',
'selectdatetime_immediately': 'true',
'additional_comments': 'testscript'
}
});
Table: sc_requestWhen: Before insertOrder: 0
Condition: current.special_instructions == "[__ABORT_INSERT_ACTION__]"
View original source
https://www.servicenow.com/community/developer-articles/add-catalog-item-to-existing-request-with-cartjs-api/ta-p/2300066