creating account by data from spreadsheet - google apps - javascript

I am working on a simple script that creates an account in the control panel of a domain - for example Gmail - and I was looking for a function in the Google apps script that creates an account automatically on inserting data to a spreadsheet
I searched the internet and I did find this though : https://developers.google.com/apps-script/class_usermanager
and the method I am using is : var user = UserManager.createUser("john.smith", "John", "Smith", "password
My question is, how can I insert the parameters from the spreadsheet that I have.
Sorry if this sounds a bit stupid I'm just new to Google apps script.

To read from the spreadsheet, you would use the SpreadsheetApp.
An example of reading a set of rows. (Let's say all rows).
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
.getValues() returns a 2D array. So you would access it by data[rowNum][colNum]. Let's say you want to add every row as a new user, you could do
for (var i in data) {
UserManager.createUser(data[i][0], data[i][1], data[i][2], data[i][3]);
}
How would you run said script? You could put all of it inside some function (function addAllUsers()) and then run it from the run menu in the Script Editor.

Related

Google App script Remove Editors From Protection

In Google Sheets I am trying to remove editors using script from all the protection except the sheet owner and for this I am using below code, but after running the code the entire protection is being removed, however in place of removing the protection I want to remove all the user from the protection except the sheet owner. Further, when the code is run only one protection is removed at a time I want to apply it for all the protection.
function remove(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)[0];
if (protection && protection.canEdit()) {
protection.remove();
}}
Any help on above will be appreciated.
The changes that you should do to make the code only allow the spreadsheet owner be able to edit a protected range were already included on the Tainake's answer to your previous question Google Sheet Remove Editors After First Edit
From the question:
Further, when the code is run only one protection is removed at a time I want to apply it for all the protection.
sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE) returns an array of objects. To remove all the the protections your code should have to iterate over all the elements of this array. One of many ways to do this is by using Array.prototype.forEach, i.e.
function remove() {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)
.forEach(protection => {
if (protection && protection.canEdit()) {
protection.remove();
}
});
}
Resources
https://developers.google.com/apps-script/guides/sheets
https://developers.google.com/apps-script/reference/spreadsheet/protection

Send value to Google Sheets via web app with formula in variable

I'm using a web app to send data to Google Sheets via Apps Script. I'm using 'appendrow' to post several variables. Everything works fine but one variable is a number, call it 'Amount'. I found out that I can type a Google Sheets type formula in my web app such as '=10-5', '=10*2', '=10/2' and when it gets posted to my Google Sheets it provides the expected result. Good! However, if I type '=10+5', I get an error in my Google Sheets. When I look at the formula bar, it shows '10 5'. Why does it not show the formula as '=10+5'? The previous examples that I gave all show the expected formula in the formula bar.
function doGet(e) {
// I cannot take credit for this script. I copied and modified it from another user.
var ss = SpreadsheetApp.openById("FILE ID GOES HERE")
var sh = ss.getSheetByName("Register"); //sheet name is 'Register'
var date = e.parameter.date;
e.parameter.date = '1/2/2023'
var amount = e.parameter.amount;
var paytype = e.parameter.paytype;
var payid = e.parameter.payid;
var maincat = e.parameter.maincat;
var subcat = e.parameter.subcat;
var explanation = e.parameter.explanation;
sh.appendRow([date, amount, paytype, payid, maincat, subcat,
explanation]);
}
So when data get passed to Google Sheets via the sh.appendRow, the amount always works correctly when it contains, for example:
'10.52', '=10-5', '=10*2', '=10/2', but not '=10+5'. Instead, I get '10 5' and shows an error in the spreadsheet cell.
You may have guessed that I am a novice when it comes to script.
Thank you for any ideas.

How to use Google Script to send an email with information collected from Google Form?

For reference: Here is my Google Form.
Here is a Google PE Blank Sheet which has been tied to the output of my Google Form (answers will output on tab Form Responses 2).
I've built up a Google Form capable of collecting a good bit of data. It is meant to be filled out by a manager requesting SAP permissions for a new hire.
They proceed through the Form and enter their primary department (SAP Stream) which leads them to the next page/section that allows the manager to check off what the employee's required permissions will be.
Sometimes, an employee will interface with multiple departments, so the option for a supporting/secondary SAP Stream exists on the second page. This can be continued as needed until all of an employee's requisite roles/permissions are collected in a Google Sheet.
In the Sheet, you will see that:
Columns A-F include basic information
Columns H-T are for the Job Responsibilities
Columns U-AG are a range for the information of one's Supporting SAP Stream
Columns AH-AT are the Supporting SAP Stream's Job Responsibilities
Columns AU-BG collect the Secondary Supporting SAP Stream
I had built Google Script language to collect each of these bits of information in variables which would then get declared as global variables so they could be passed along to an HTML page in the App Script.
Finally, an email consisting of this HTML page would be sent out to the manager in charge of designating SAP permissions.
In previous iterations (which were much simpler), I used an IF statement to check whether a column at the end of the row was empty.
// Loop over the rows
data.forEach((row,i) => {
// Identify whether notification has been sent
if (row[59] === '') {
If it was, the Script would check the Sheet, collecting all of the aforementioned information, and send an email. Then, it would populate that last cell with "Notification Sent" so that the next time the Form was submitted and the Script checked, it would skip sending out a redundant email (and we would have a record that the process went through successfully).
The latest version included variables for
function jobResponsibilities(a){
var z = a.range.getRow();
var valuesA = a.range.getSheet().getRange(z,8,1,13).getValues();
var jobResponsibilities = valuesA.join(' ');
console.log(jobResponsibilities);
}
function supportingSAP(b){
var y = b.range.getRow();
var valuesB = b.range.getSheet().getRange(y,21,1,13).getValues();
var supportingSAP = valuesB.join(' ');
}
function secondaryJob(c){
var x = c.range.getRow();
var valuesC = c.range.getSheet().getRange(x,34,1,13).getValues();
var secondaryJob = valuesC.join(' ');
}
function secondarySAP(d){
var w = d.range.getRow();
var valuesD = d.range.getSheet().getRange(w,47,1,13).getValues();
var secondarySAP = valuesD.join(' ');
}
Collecting the four varying types of information. I used a getRange in order to scope out the exact parts of the Sheet which would have this information and join them together so that the variable could be pulled into the email in a simple table format.
For some reason, upon Form submission, the Notification IF doesn't seem to be running and the email never gets sent.
Is it a problem with the way I've ordered things? Did I improperly build the functions off what you showed me? Is it something as simple as my brackets at the bottom?

How to create a new row at the end of an existing sheet in Google Spreadsheets after completing a Google Form?

I'm trying to save responses from a linked Google Form into an existing Google sheet. More precisely, the spreadsheet shows employee's time off requests with the employee's Reason for leave, Number of days requested, Date Requested, Name of Manager, etc. Basically, the form asks the employee for these information.
Thanks!
What I'm trying to achieve here is saving the response information into the already created spreadsheet. According to Google's documentation, the only two options are: 1) Create a new spreadsheet: Creates a spreadsheet for responses in Google Sheets
2) Select existing spreadsheet: Choose from your existing spreadsheets in Google Sheets to store responses
In case of option #2, I can save responses in the same spreadsheet BUT it saves them in a new sheet; I'm trying to save the responses in the same
sheet.
I know that Google Form has a Script Editor. Would it be possible to run a function that sends the responses to the Spreadsheet? Maybe something like this?
function sendToSpreadSheet(e)
{
var ss = SpreadsheetApp.openById("abc1234567");
// Send response to spreadsheet
// Populate cells accordingly
}
I don't have much experience with Google Forms, so I'm not sure how to approach this issue. Any suggestion(s) is greatly appreciated.
Try this:
You have to supply the Spreadsheet Id and SheetName. And also create a onFormSubmit trigger for the spreadsheet.
function saveResponse(e) {
SpreadsheetApp.getActive().getSheetByName('SheetName').append(e.values);
}
or
function saveResponse(e) {
SpreadsheetApp.openById('id').getSheetByName('SheetName').append(e.values);
}
onFormSubmit Event Object for Spreadsheet
You can create trigger with something like this:
function createSetResponseTrigger(){
createTrigger('setResponse');
}
function createTrigger(funcname) {
if(!isTrigger(funcname)) {
ScriptApp.newTrigger(funcname).forSpreadsheet(SpreadsheetApp.getActive()).onFormSubmit().create();
}
}
and this
function isTrigger(funcName){
var r=false;
if(funcName){
var allTriggers=ScriptApp.getProjectTriggers();
for(var i=0;i<allTriggers.length;i++){
if(funcName==allTriggers[i].getHandlerFunction()){
r=true;
break;
}
}
}
return r;
}
or you can just create it manually with Edit Menu/Current Project Triggers.

Bad value when trying to execute google Apps Script

I am trying to execute a simple Apps script to retrieve data from my google sheet. However, I get the error:
Bad value (line 2, file "Code", project "Untitled project")
when I paste the link:https://script.google.com/macros/s/AKfycbw8_1qGhuEMvfOEbLAx69x4fXyPl4sKQc4dvka81i5t42MkZpU/exec (the link provided for my web app after publishing) into my browser and hit enter.
However,when I click "test web app for your latest code" after publishing, it displays the JSON correctly without any issues. My app script code is as follows:
function doGet() {
var ss = SpreadsheetApp.openById('1gQKvGO0fhcrgqeke8HkUqm5Mb9dXWbaflIDmIo-pWcA');
var sheet = ss.getSheets()[0];
// Get the range of cells that store employee data.
var employeeDataRange = ss.getRangeByName("Range1");
// For every row of employee data, generate an employee object.
var employeeObjects = getRowsData(sheet, employeeDataRange);
return ContentService.createTextOutput(JSON.stringify(employeeObjects)).setMimeType(ContentService.MimeType.JSON);
}
Other posts mention that the spreadsheet id must be correct but I am pretty sure my id is correct.
From your question, it seems that you have changed the code but you have not republished it with latest version, so when you "test web app for your latest code", it works fine but when you use your publishing link, it crashes.
go to : publish > deploy as webapp > select project version to new and update the project.

Categories