Home > other >  Saving document to specific google drive folders depending on variable name
Saving document to specific google drive folders depending on variable name

Time:09-16

How should I approach the problem of saving a file to a specific folder depending on the result of a variable?

For example,

Say I have 3 clients Bob, Billy and Ben. And on google drive, I have corresponding folders for each client, so "BobFolder", "BillyFolder" and "BenFolder".

If the name happens to be "Bob" during a loop, then I would like to save my file to "BobFolder". Since I am using DriveApp.getFolderById(), I am thinking the only approach is to use switch statements (or similar logic) using the folder IDs. Or is there another way to do this?

Appreciate any help I can get!

Here is roughly how I would grab the client name from my google sheet:

// get data range
  const rows = invSh.getDataRange().getValues();

  var toIndex = getColumnId(invSh, "To") - 1;

rows.forEach(function (row, index) {
  // skip header row logic

// skip rows that already have document created and linked logic

    // make copy document of template and get body (this is also where i would add logic to figure out the destination folder depending on the client)
    const copy = googleDocTemplate.makeCopy(`INVOICE_${row[invNumIndex]}`, destinationFolder);
    const doc = DocumentApp.openById(copy.getId());
    const body = doc.getBody();

// add client name to doc
body.replaceText('{{to}}', row[toIndex]);
}

So during the loop, each row will call row[toIndex] which would could for example be:

row[0] -> 'Bob'

row[1] -> 'Billy'

etc.

CodePudding user response:

Do you mean something like this?

var IDs = {
    'Bob':  'ID-1',
    'Bill': 'ID-2',
    'Ben':  'ID-3',
}

var folder_id = IDs['Bill'];

console.log(folder_id); // output: ID-2

var the_name = 'Bob';
folder_id = IDs[the_name];

console.log(folder_id); // output: ID-1

And you can use:

var dest_folder = DriveApp.getFoldersByName('BobFolder').next();

But make sure that you have just one folder with name 'BobFolder' on your Drive. Otherwise the result could be random. This is why to use ID is a better idea.

CodePudding user response:

If you want to find the folder by its name, you would do this:

const clientName = row[toIndex]; // e.g. Bob
const folderName = `${clientName}Folder`;
const folderIter = DriveApp.getFilesByName(folderName);
if (folderIter.hasNext()) {
  const destinationFolder = folderIter.next();
  // Rest of your code
}

As Yuri Khristich said, though, this might not point to the right folder if there are multiple folders with that name in your Drive. In this case, using the folder id might be a better approach (see getFolderById).

Also, if all your possible destination folders are children of a given folder, you could use Folder.getFoldersByName(name) instead. This could help if you have other folders with your desired names outside that specific parent folder.

  • Related