Look Up Folder IDs
The following sample shows how to use a cache to help you look up folder IDs. Mulitple searches are often required to look up folders. Using a cache could provide a simpler way to find your folder IDs.
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
In this sample, folder names are used as the cache keys and the folder IDs are the actual cache values. This sample looks up folders by their folder name and their parent folder name. This sample includes four functions: folderCacheLoader, getFolderCache, folderKey, and getFolder.
You would include this sample code in a custom module that is called using the options.loader
parameter of the Cache.get(options) method.
const FOLDER_CACHE_NAME = 'folder_cache';
function folderCacheLoader(context) {
const PARENT_FOLDER_ID = 0;
const FOLDER_NAME = 1;
const folderCacheKey = context.key.split('/');
const parentFolderId = folderCacheKey[PARENT_FOLDER_ID];
const folderName = folderCacheKey[FOLDER_NAME];
var folderId = null;
search.create ({
type: search.Type.FOLDER,
columns: ['internalid'],
filters: [
['parent', search.Operator.ANYOF, parentFolderId],
'AND',
['name', search.Operator.IS, folderName]
]
}).run()
.each(function(folder) {
folderid = folder.id;
return false;
});
if (!folderId) {
var folder = record.create({
type: record.Type.FOLDER
});
folder.setValue({
fieldId: 'parent',
value: parentFolderId
});
folder.setValue({
fieldId: 'name',
value: folderName
});
folderId = folder.save();
}
return folderId;
}
function getFolderCache() {
return cache.getCache({
name: FOLDER_CACHE_NAME
});
}
function folderKey(folderName, parentFolderId) {
return[parentFolderid, folderName].join('/');
}
function getFolder(folderName, parentFolderId) {
return getFolderCache().get({
key: folderKey(folderName, parentFolderId),
loader: folderCacheLoader
});
}