Whatever your reasons may be, there may come a time when you need to dynamically add an additional variable to a request item after the original request has been entered by the user. This could be for populating additional information that is not available at the time the request is made or if you are breaking up a single request that contains a list into multiple individual requests that can be operated on individually.
The challenge with doing this is that there is a relationship between four different tables that needs to be setup to ensure that the variable is associated with the request properly. At the top is the Request Item table itself (sc_req_item). Ultimately, this is where the variables will be referenced on any subsequent form displays. The other three tables create the relationship between the request item, the questions and the answers. These other tables are sc_item_option_mtom, item_option_new and sc_item_option.
Working backwards, we ultimately need to build up the relationship between the request item and answers associated with the particular request item. Capturing this relationship is the responsibility of the sc_item_option_mtom table. The sc_item_option_mtom table is a many-to-many table that has an entry that relates every single answer (sc_item_option) to its respective request item (sc_req_item). (You can review many to many relationships in the ServiceNow wiki). In addition, each entry in the Answer tables (sc_item_option) has a reference to the particular question it answers (item_option_new).
To formalize this, I’ve put together a bit code that takes a request item, variable name, variable value and (optionally) a catalog item to associate a question and answer to a particular request item.
function addOptions(reqItemID, varName, varValue, catItem)
// Get a reference to the request item table using the sys_id of the request item
var gr_item = new GlideRecord(‘sc_req_item’);
gr_item.addQuery(‘sys_id’, reqItemID);
gr_item.query();
// Assuming we found a matching request…
if (gr_item.next()) {
// Find the correct question
var gr_option = new GlideRecord(‘item_option_new’);
gr_options.addQuery(‘name’, varName);
// If the question is associated with a catalog item, keep that relationship
if (catItem != ”) gr_options.addQuery(‘cat_item’, catItem);
gr_options.query();
// If we found a matching question…
if (gr_options.next()) {
// Get a reference to the answers table and insert a new answer
var gr_answers = new GlideRecord(‘sc_item_option’);
gr_answsers.initialize();
gr_answers.item_option_new = gr_options.sys_id; // Map the answer to its question
gr_answers.value = varValue;
gr_answers.insert(); // Insert the record
// Now build the relationship between the answer and the request item
var gr_m2m = new GlideRecord(‘sc_item_option_mtom’);
gr_m2m.initialize();
gr_m2m.sc_item_option = gr_answers.sys_id;
gr_m2m.request_item = reqItemID;
gr_m2m.insert(); // Create the new relationship
}
}
}
You must log in to post a comment.