Google Apps Script Bad Value - javascript

I'm getting a "bad value on line 4"... I don't know why. I'm trying to make a Google sheet that automatically opens to an assigned tab based on gmail address for a large team. Please help!
function onOpen() {
var email = Session.getActiveUser().getEmail();
var username = email.slice(0,-9);
var ss = SpreadsheetApp.openById(username);
SpreadsheetApp.setActiveSpreadsheet(ss);
}

I suspect here your issue is a misunderstanding of the function '.openById()'.
This function is designed so that you identify and open the spreadsheet using a spreadsheet ID (The alphanumeric part of the URL when opening a sheet, such as "abc1234567"). From context and your use of the variable 'username', I think that instead you're somehow trying to open it based on an email ID (Such as user#domain.com).
Incidentally, you won't be able to open the sheet in an assigned tab using Scripts. That's not what it does, and it's unable to manipulate a users browser. Perhaps an extension for Chrome would be closer to what you're looking for.

Related

google script to add information to sheet , script and bootstrap form using showModalDialog

I already have the html form made from bootstrap, however, when I am trying to use the click button to add the information to google sheet from the html form it is not working
this is my GS function
function addRow(rowData){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("STUDENTS");
ws.appendRow([rowData.names,rowData.phones,rowData.idnumber,rowData.fivehr]);
and this is my function on html file
function afterButtonClick(){
var name = document.getElementById("studentnames");
var phone = document.getElementById("phonenumber");
var idnumber = document.getElementById("ID-number");
var fivehr = document.getElementById("fivehr");
var rowData = {name: name.value,phone: phone.value, idnumber: idnumber.value, fivehr: fivehr.value};
google.script.run.addRow(rowData);
}
document.getElementById("ADD").addEvenListener("click",afterButtonClick);
example for the line for the variable
<input style="font-weight:bold" type="text" class="form-control" placeholder="Student Name" aria-label="Name" id="studentnames">
the html form is perfect the way I want it, but the function on html is not adding the data to sheet
I am following a youtuber but it is not working at all, I did some changes on the wording but I guess I am missing something, if anyone can look at it and tell me my mistake, I appreciate the help thank you
if fivehr is a datetime then that is a restricted parameter and cannot be passed using google.script.run. If it is a restricted parameter then the entire object will be nulled out. Read about it below:
https://developers.google.com/apps-script/guides/html/communication#parameters_and_return_values
Keys of your object should be same.
You've to use rowData.name and rowData.phone.
ws.appendRow([rowData.name,rowData.phone,rowData.idnumber,rowData.fivehr]);
In order to see what is the problem, you can firstly go to DevTools > Console and see if there is an error message in your client side functions. If not you go to Script Editor > Executions and see if your server side functions returned an exception.

Google Sheets "Script Function Could Not Be Found"

First time posting here and a newbie at javascript, so hoping this is a very simple fix. I have created an appendRow script (after following a few different examples and amending them for my use). The intention is to have 4 cells at the top of a Google Sheet that are automatically added to the bottom of data in columns A, B, C & D.
Code:
var headers = ['Today' , 'Month' , 'Total Value' , 'Cash Invested'];
var data1 = ['Today' , 'Month' , 'Total Value' , 'Cash Invested'];
var data = [headers , data1];
function putMultipleValues()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("VG Investment Value");
sheet.appendRow(['=a5','=b5','=c5','=d5']);
}
All is working ok, except that the only way I have found to connect the button to the script is by using the 'Select function' name "putMultipleValues". If I use the name of the script (that I have given it) - "VG Table", a "script could not be found" error shows.
This would not be an issue, except I would like to use an almost identical script on a different, almost identical, sheet. The trouble is that this new script also has the 'Select function' name "putMultipleValues" so both scripts fail.
Does anyone know how to change the button so that it links to the script's name rather than it's function?
Many thanks in advance.
Hi and welcome Markrc !
I don't have much experience in Google Script, but from what I understood, a Spreadsheet (and its sheets) is connected to a Script Project.
This Script Project can contains one or more script files.
Each Script files can one or more functions.
The function is what Google Sheet will call a script. (I know, this is a bit confusing)
You can link a script to a button, wich means you can link a function.
However, if you use global variables in your script, the function can access to it (as you noticed). You can link different buttons to different scripts (functions), but you can not link a button to a Script Project or a Script File.
I am not 100% sur of this, but this is how I think it works. If anyone could confirm it, it would be great.
Hope it helped !

How to ask for user permission from a Spreadsheet for filebound script?

I have a simple Google Spreadsheet with some code behind - that is, my script is bound to the Spreadsheet file (no standalone code, neither code deployed as add-on). When an user edits one given column, the scripts runs an email check (that is, it compares the current user email with the one saved on the table). The code is as follows:
function showDialog() {
var ui = SpreadsheetApp.getUi();
var html = HtmlService.createHtmlOutput("Apenas o usuário que registrou a emissão da passagem pode realizar alterações em seu registro!<br><input type=\"button\" value=\"Fechar\" onclick=\"google.script.host.close()\" />")
.setWidth(400)
.setHeight(90);
ui.showModalDialog(html, 'Edição não permitida!');
}
function onEdit(e){
var ui = SpreadsheetApp.getUi();
var this_file = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/key_to_my_file/edit');
var main_sheet = this_file.getSheetByName("Tickets");
var edited_range = e.range;
var edited_row = edited_range.getRow();
if(e.user != main_sheet.getRange("B"+edited_row).getValue()){
edited_range.setValue(e.oldValue);
showDialog();
}
}
My issue is that, being the owner of the script, I have granted it all the permissions it needs - therefore, my dialog is shown properly either via the Script Editor or the Spreadsheet itself, editing data I'm not allowed by the script rules to edit.
When it comes to other users, though, it doesn't work. I can't see any error in the execution logs for the OnEdit trigger I have, nothing. If the user, then, opens the Script Editor, runs the function showDialog, grants the permissions in the following box, it all starts to work.
I can't expect, though, that non technical users will be able to do all that. I need a way to either be able to follow those steps. Also, I have to use a custom dialog, rather than the usual ui.alert() (which works finely, by the way, no permissions issues), because I need a non-blocking alert.
I'm basing my comprehension on this matter on google apps script docs page, in particular the session "Custom sidebars".
How can I either get rid of the need for permissions, or force the user of my spreadsheet to grant them from start?

HTML Function displaying as plain text

I have been working on this for quite some time, and have basically been teaching myself HTML, so I apologize if the code is sloppy or if this is a simple fix. Here is what I am attempting to do, and the problem I am running into:
Take Google Form responses, generate an email based on those responses and dynamically email a certain person in my organization based on the location response(this part is done and working, just adding for context). Then create a survey response that sends info back to the original responder, sent from the administrator that the form was sent to. This is the js that I have running, that is working when it is ran in the google project:
function getid() {
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/a/raytownschools.org/spreadsheets/d/1YWHu_yKn5bqq63x1A4e4-vBUtZANj-xjeF07IBpHP64/edit?usp=sharing');
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
var sheet = spreadsheet.getActiveSheet();
var lastRow = sheet.getLastRow();
}
When I attempt to run that in my HTML code, and insert it into the element, it is simply inserting that code as raw text. HTML isn't running the function, or returning the data that it should be (and does return when ran outside the HTML code as a js app).
I can post the full HTML code if that would be helpful. Hopefully someone on here can help me out.
What you have there is a Javascript function. There aren't functions in HTML, HTML is a markup language.
You must add that function inside Javascript tags like this:
<script type="text/javascript">
function getid() {
var spreadsheet = SpreadsheetApp.openByUrl('https://docs.google.com/a/raytownschools.org/spreadsheets/d/1YWHu_yKn5bqq63x1A4e4-vBUtZANj-xjeF07IBpHP64/edit?usp=sharing');
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
var sheet = spreadsheet.getActiveSheet();
var lastRow = sheet.getLastRow();
}
alert( getid() );
</script>
Take a look at here, on how to use javascript.
Edit
Seems like that code you're trying to execute is for Google Apps Script. I think you must execute it inside the Google script editor, because they don't make this API available for regular websites. Here is a running example with your code.

TypeError: Cannot read property "1" from undefined

I have some very simple code that is triggered by a google form (see http://goo.gl/lFHi3j) that asks for 2 email addresses. The code works fine when the email address is hardcoded (see commented email below) but when I try and obtain the email using e.values (when the form is submitted) is get the following error
Execution failed: TypeError: Cannot read property "1" from undefined.
(line 3, file "Code").
I've searched this forum but can't find a solution to this problem. Can anyone please help.
function onFormSubmit (e) {
// var email_address_ = "pian1966#gmail.com";
var email_address_ = e.values[1];
// Send the email
var subject_ = "Andy's Report";
var body_ = "Here is Andy's report...";
MailApp.sendEmail(email_address_, subject_, body_, {htmlBody: body_});
}
There is no e.values[1].
That is the answer to the question as to why you are getting that error.
Do a console.log(e) and familiarize yourself with what e consists of by looking at the log results in a browser debugger.
From there you can determine for yourself if e.values even exists as an array. Then go from there.
Thanks for the responses which all helped me find a solution to the problems I was having. Here's what I've discovered as I've worked on a solution:
The Google App Script must be created (as a blank script) from
responses spreadsheet and NOT out of the form itself!
In Google Forms, the developer has the option of unlinking their
responses spreadsheet and sending responses to new results
spreadsheet. If this option is selected then a new script needs to
be created from the new results spreadsheet and the code must be
copied/moved into the new script. Of course this means that a new
trigger must be created and the script needs to be authorized to
run.
Once a user submits a form, they can be given the option to
edit/correct their submission. Unless EVERY field is edited, the
script thinks the unedited fields are blank and writes "undefined"
into the resulting Google Doc. I've therefore disabled the "Edit"
option in my form to get around this.
If the user skips over irrelevant fields (leaves them blank) then
the e.values numbering order is thrown out. I have therefore made
every field compulsory with the comment that the user enter 'n/a' if a
field doesn't apply.
Having worked through these issues my form now works perfectly (albeit a little clumsily with all questions being compulsory). I would be very grateful if anyone has any suggestions on how to get around the Editing and and Blank Field problems.
(Thanks to TJ Houston for his original script)

Categories