The requirement was to create child folders under a previously decided parent folder in the NetSuite file cabinet. We should reuse the existing folders if a folder with the requested name already exists and no duplicate folders should be created. These folders can be used to store attachments related to records. Refer to the following code sample:
/**
* Function to create a new folder in file cabinet
* @param {Name of the folder} name
* @param {Internal ID of the parent folder} parentFolderId
* @returns folder ID
*/
function createFolder(name, parentFolderId) {
let folderId;
let folderSearch = search.create({
type: search.Type.FOLDER,
filters: [
['name', 'is', name],
'AND',
['parent', 'anyof', parentFolderId]
],
columns: ['internalid']
});
let searchResult = folderSearch.run().getRange({ start: 0, end: 1 });
if (searchResult.length > 0) {
folderId = searchResult[0].getValue('internalid');
} else {
try {
let folderRecord = record.create({
type: record.Type.FOLDER,
isDynamic: true
});
folderRecord.setValue('name', name);
folderRecord.setValue('parent', parentFolderId);
folderId = folderRecord.save();
} catch (e) {
log.error('Error creating folder', e.toString());
}
}
return folderId;
}