Chris Pearson
Tera Contributor

Disclaimer: The ideas, thoughts, and opinions in this post reflect my own views and do not necessarily represent the views of my employer, Accenture. 

Every developer should keep a quiver of code snippets to reuse. Nobody needs to be reinventing the wheel at this point. There are enough developers that have done amazing things on the platform that chances are there's a code snippet out on the Community site or in the Docs site that is pretty close to what you're trying to get done.

I'll be putting a few of my favorites out here over the next few blogs. 

This first one is not necessarily something that I created myself, but ends up being used quite often when building integrations which need to order a catalog item, or even ordering an item triggered from processing an inbound email. This capability has been around for a while but using the newer CarJS allows you to now set the Requested for on the catalog item as you order it which is a really nice feature. 

// This script will order a catalog item by script and set the requested for 
// What you'll need: 
// The sys_id of the catalog item you want to 'order' 
// The sys_id of the user that you're ordering the item on behalf of 
// it is your responsibility to write whatever code necessary to get that user sys_id 

var userID = 'this_needs_to_be_the_sys_id_of_the_user'; 
  
// Generate a shopping cart 
var cart = new sn_sc.CartJS(); 

// Create an object to assign values to variables in your catalog item 
// Pay attention to each variable your catalog item has and its variable type. If it's a reference type, 
// you'll need to set the value of that variable with a sys_id of some kind for example. 
// Note: The first attribute of this object needs to be the sys_id of the catalog item you are ordering. 
var itemObj = { 
    'sysparm_id':'enter_the_sys_id_of_the_cataog_item_here', 
    'sysparm_quantity':'1', 
    'variables':{ 
        'short_description':'this is the short description', 
        'description':'this is the description', 
        'variable_name':'variable value' 
    } 
};
 
// Add our item to the cart, change the requested for to the proper user and checkout 
cart.addToCart(itemObj); 
cart.setRequestedFor(userID); 
var submitDetails = cart.checkoutCart();