Empty or wrong values in App Script onFormSubmit event - google-apps-script

I have a google form with some questions like:
This field is set as required. The problem is that I cannot see the results of this field in the corresponding spreadsheet:
I have a trigger to run a function (from the spreadsheet code editor) when an answer is sent from the form:
And this is the function triggered:
function copyFormContents(e) {
Logger.log(JSON.stringify(e))
}
And this is what I see in the log:
{
"authMode": "FULL",
"namedValues": {
"My Question": [
"",
"Another answer"
]
},
/ ******* /
}
As you can see, My Question appears with two entries, and sometimes empty. I have tried by switching the question to required and not, but this keeps happening. What am I doing wrong? Please help

According to Victor M Herasme Perez it looks like the problem was solved by creating a new form and linking a new sheet to save the responses given the fact that deleting some questions was the actual root cause of the sheet showing incct data.
This is actually a common behavior that has appeared multiple times in different forums like in Google's community.
There is no official documentation about this specific issue even though it is something expected as you can see in the explanation from the product expert in Google's community post.
As a recommendation I think it would be best to add this behavior to Google's issue tracker for evaluation.

Related

Save Gmail Attachments on Google drive - unknown file type

I looked for previous questions on this subject and found some posts from a few years ago. They don't exactly match my problem and when I try them I get more run errors than the script I am using. In my case, my script creates the files but they show up in my google drive as "unknown file" and can't be opened or previewed in Google drive. However, if I download the file to my pc, it opens and previews correctly and without any problem. How do I correct the "unknown" designation in my Google Drive?
I've tried a lot of possible solutions but either they get run time errors or I end up with an "empty" file.
Does anyone have any ideas on why this is happening or how to correct the unknown files attribute?
//pasted by Cooper as an example
function putyourcodehere() {
//this was posted via a ctrl-K
}
Save Attachment to a folder
function lfunko() {
const query = 'subject:ThisIsATestMessage';
Gmail.Users.Messages.list(gobj.globals.calendarid, { q: query }).messages.forEach(m => {
GmailApp.getMessageById(m.id).getAttachments().forEach(a => {
DriveApp.getFolderById(gobj.globals.testfolderid).createFile(a.copyBlob()).setName(a.getName());
})
})
}
gobj.globals is an object of global variables I use so that I don't have to redact them when used within answers that will be posted on SO. Just treat them as things you will have to replace with your own local variables. I used gobj.globals.calendarid because that's my email address which is what they want for the userid
Of course you will have to enable the Gmail API

Google Classroom API Create Material

I am aware that there are multiple questions essentially asking the same thing, but part of the problem I've identified is a lack of detail in the questions, so I'm going to try here, since I think I've exhausted all possibilities.
In the newer Google Classroom, there is a Classwork Tab/Page. This is new, and replaced an older "About" page. In this page, as a regular web user, you can create various materials, including one simply called "Material." This is done by clicking the create button and choosing "Material".
These materials contain any combination of title, description, and attached files/links.
However, when using the API, while I can access any OTHER type of Classwork via:
Classroom.Courses.CourseWork, no attempts to find these items (or create them via the API) has been successful. I've successfully created Assignments (a variant of CourseWork using:
Classroom.Courses.CourseWork.create({
"creatorUserId":'me',
"state":'draft',
"courseId":cid,
"title":'test item',
"workType":"ASSIGNMENT",
"materials": [],
}, 'myClassCode');
}
The enum for workType according to the API only contains:
I've tried omitting the workType (receive error saying I need to include it), using various guesses like MATERIAL, NONE, ABOUT, and null (all receive errors for invalid types).
I can query the list of CourseWork and find all of my entries that are questions or assignments but have found no access to the other items, which are current and active in the Classwork page for the class.
It's possible that this simply isn't accessible via the API, but I'd like to confirm. Any advice would be appreciated.
I am running as SuperUser and everything else seems to be working fine.
You are right, at the moment it is not possible to create course materials through Google Classroom API.
Indeed, there is a feature request for it already:
https://issuetracker.google.com/issues/127591179
I suggest you to give it a star to increase visibility and get updates on the implementation status of the feature.
Here is code that I have been using
/------------------------------Create Coursework Material-----------------------------------
function createCourseworkMaterial (id, cTitle, cDescription, topicId) {
var courseArgs = {
"title": cTitle,
"description": cDescription,
"state" : "DRAFT",
"topicId": topicId
};
try{
Classroom.Courses.CourseWorkMaterials.create(courseArgs,id);
}catch(e){
console.error('Classroom.Courses.CourseWorkMaterial.create() yielded an error: ' + e);
}
}

Trouble Adding grades using Google Classroom API and Google Apps Script

I am unable to change grades using the Google Classroom API. When I run the code below, lines 2 and 3 run fine. However, line 4 fails with the following message: #ProjectPermissionDenied The Developer Console project is not permitted to make this request.
1) var studentSubmission = {'assignedGrade':'1'};
2) var studentSubmissions = Classroom.Courses.CourseWork.StudentSubmissions.list(courseId, courseWorkId, {userId:'studentEmail#apps.matsuk12.us'});
3) var studentAssignmentId = studentSubmissions['studentSubmissions'][0].id;
4) Classroom.Courses.CourseWork.StudentSubmissions.patch(studentSubmission, courseId, courseWorkId, studentAssignmentId,{'updateMask':'assignedGrade'});
When I go to Project Properties and look at the scopes, here is what I see:
https://www.googleapis.com/auth/classroom.courses
https://www.googleapis.com/auth/classroom.coursework.students
https://www.googleapis.com/auth/classroom.profile.emails
https://www.googleapis.com/auth/classroom.profile.photos
https://www.googleapis.com/auth/classroom.rosters
https://www.googleapis.com/auth/spreadsheets
I am trying to access my own Google Classroom using a container bound script (spreadsheet). Seems like if I have access to the assignments, I should have access to add a grade. Not sure why I can't add the grade. Is there anything I can do to get this code working? The end goal is to be able to grade assignments using a form (not a google form) and have the score automatically pushed to Google Classroom.
I saw a related post that mentions a solution, but it is not clear how to implement it: Permission denied using Classroom.Courses.CourseWork.StudentSubmissions.list(4140802199, 4801051201);
I also see a related bug report here: https://issuetracker.google.com/issues/67748271 (I'm not sure though if this really is a bug, or if this is just how the Google Classroom API works, or if I'm just doing something wrong)
From the posts you linked someone posted this code:
function createCoursework (id) {
Classroom.Courses.CourseWork
.create(id, {
// doesn't work but triggers permissions correctly "courseId": id, "title": 'foo', "description": 'desc', });
}
Essentially you need to put this code somewhere in your projects code. Then, using the, Run menu, execute that function. It won't do anything, but it will initialize the authorization request from google; by means of a popup. After that you should be good to delete that function and use that scope.

New Google Sheets custom functions sometimes display "Loading..." indefinitely

SPECIFIC FOR: "NEW" google sheets only.
This is a known issue as highlighted by google in the new sheets.
Issues: If you write complex* custom functions in google-apps-script for google sheets, you will occasionally run into cells which display a red error box around the cell with the text "Loading..."
Google has suggested:
If this occurs, try reloading the page or renaming the function and changing all references to the new name.
However for other developers experiencing this issue (and who are unable to escape the "loading..." error), I've written my findings in the answer below on how to get past this (with limitations) consistently.
*We're treating this question as the canonical answer for Google Sheet's indefinite "Error... Loading data" problem. It's not limited to complex or slow functions.
Important Tip: Create multiple copies of your entire spreadsheet as you experiment. I have had 3 google spreadsheets corrupted and rendered completely in-accessible (stuck in a refresh loop). This has happened when I was experimenting with custom functions so YOU HAVE BEEN WARNED!
You will want to try one or many of the following ways to fix this issue:
As suggested by google, try re-loading the spreadsheet or re-naming the function or changing the parameters in the cell to see if this fixes the issue.
Surround ALL your custom functions in a try-catch block. This will help detect code issues you may not have tested properly. Eg:
try{
//methods
}catch(ex){
return "Exception:"+ex;
}
Revert to the old sheets and test your functions and check for any other type of error such as an infinite loop or invalid data format. If the function does not work in the old sheets, it will not work in the new sheets and it will be more difficult to debug.
Ensure NONE of your parameters refer to, can expect to or will ever contain a number larger than 1 million (1000000). No idea why but using a number larger than a million as any parameter will cause your function to fail to execute. If you have to, ask the input to be reduced in size (maybe divide by 1000 or ask for M instead of mm).
Check for numeric or floating point issues where numbers may exceed a normal set of significant figures. The new sheets seems to be a little glitchy with numbers so if you are expecting very large or very complex numbers, your functions may not work.
Finally, if none of the above work, switch to the old google sheets and continue working.
If you find any other limitations or causes for functions to fail to execute, please write them below for me and other users who are heavy g-sheet users!
I also had the infinite loading issue with the following function.
// check if an item can be checked off
function checkedOff( need, have ) {
var retStr = "nope";
if( have >= need ){
retStr = "yep";
}
return retStr;
};
Turns out you shouldn't have a trailing ";". Removing the semicolon solved the problem.
// check if an item can be checked off
function checkedOff( need, have ) {
var retStr = "nope";
if( have >= need ){
retStr = "yep";
}
return retStr;
}
This runs as one would expect.
FWIW, I just ran into this and the culprit ended up being a getRange() call that pulled several thousand rows into an array. Periodically it would get hung on the "Loading..." message.
I worked around it by putting that range into the document cache. It's a little kludgy because the cache only stores strings, not arrays, but you can force it back into an array using .split(',') when you need to access the array.
(In my case it's a single array. There's probably a way to do it using a double array, either by sending each row or column into its own cache, or reading the cache value back N items at a time, each N becoming its own array.)
Here's the relevant bit from my code:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet"); //search the "mySheet" sheet
// is the big list already in the cache?
var cache = CacheService.getDocumentCache();
var cached = cache.get("columnValues");
if (cached != null) {
var columnValues = cached.split(','); // take the cached string and make it an array
} else { // it's not in the cache, so put it there
var column = 1; // the column with your index
var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); // first row is header
cache.put("columnValues",columnValues,60000); // this forces the array into a string as if you used .join() on it
}
This is definitely a bug in Apps Script -- getRange() shouldn't hang without a timeout or error message. But at least there's a workaround. Here's the bug I opened against it, where I've also put the full code.gs from my sheet.
One cause: Permissions needing authorizing.
As far as {this problem, better phrased the cell result(s) of a custom function displaying the disgustingly-vague message ‘Loading... Error: loading data...’}, indeed in the case where all instances of the same/similar custom function call displaying this error, is that Google Sheets needs permissions to run the script (often additionally: meaning in the past it didn't need these), so instead of {acting appropriately: then prompting the user for these permissions else returning that error}, Sheets instead hangs with this disgustingly vague error.
Additional permissions can be needed from 1 or more:
Google App Scripts has since rewriting their permission structure --how this problem now just happened to me, per my internal note O80U3Z.
Your code or some library it uses made changes to require more access ...but in this case you have a much better chance of guessing the cause of this disgustingly-vague error, so hopefully won't be reading here.
To fix, I explicitly ran my GAS spreadsheet code by both: clicking one of my custom menu functions and, in the ‘script editor’, running one of my custom JS functions notably the ‘onOpen()’ since that is most comprehensive. The first promoted me for indeed new permissions, via popup ‘Authorization RequiredThe application "MM6ZBT(MM6Z83 script)" needs authorization to run.’, though onOpen() also did this in cases of GAS revising its permissions since we used that sheet. Then, as I was still getting this ‘Loading...’ error, I reloaded the web page (so the sheet), and, at least for these cases of this disgustingly vague error, it was gone and the computations worked fine :-)
TL;DR - Try duplicating the sheet tab and delete the old one
I struggled with this issue today, and tried some of the approaches mentioned. For various reasons, renaming the function wasn't possible for me.
It was very clear that if I called a my function like this in cell X25:
=myFunction("a", 1, "b", 2, "c", 3)
The cell would be stuck "Loading...", while just changing a parameter slightly (e.g. converting a number to a string) the cell would evaluate fine.
=myFunction("a", "" & 1, "b", 2, "c", 3)
Just copying the code into another cell (e.g. X24) and executing it there seemed to bypass the problem. As soon as I moved it back to the original parameters or cell, it got stuck "Loading..." again.
So I would assume it's some kind of caching of "Cell ID", function and parameters that go bonkers on Google's side.
My good-enough solution was to simply duplicate the Sheet tab, delete the old one, and finally rename the new one back to the original name. This solved the problem for me.
I also had the "loading data..." error but none of the fixes described here worked for me. It didn't seem to be caused by the issues described here. In my case, I narrowed it down to a specific floating point operation issue (it looks like a real bug in Google Sheets to me), and documented one possible work around at
Google Sheets / Apps "Loading data" error: is there a better workaround?
To summarize (at the request of commenter Steve), if a cell with
= myfunction(B10)
generated a "loading data" error, then for me it could be fixed by wrapping the argument in a "value()" function:
= myfunction(value(B10))
which converts the number in cell B10 (which seemed like a normal number but generated problems somehow) into a normal number that works fine.
I also had the problem that you explained. It seems that it can be caused in more than one way.
I ended up finding that my custom function was displaying that error because it relied on data from an =IMPORTRANGE() call, and that call was failing.
I eventually found that the =IMPORTRANGE() call was failing because I had forgotten to update the URL that it was importing from when I had uploaded a new version of that imported-from sheet. It seems that trying to IMPORTRANGE from a trashed file can cause the infinite "Loading..." error.
Update 2022
It looks like this bug is still happening. I tried ALL the solutions mentioned here but none worked.
What worked was to start with a blank slate. I recreated the file, copy-pasted my data, reapplied my preferred style and format, and lo-and-behold the sheet finally managed to pull the data using my custom functions.
This is a definitely a bug on Google's end - and it's all the more annoying because they removed the "Report a problem" button from the "Help" section.
Nevermind
The newer sheet has stopped working too. This is so annoying ..
The problem is that when a custom function formula cell starts showing Loading..., the custom function does not get called at all. The code in the script project thus does not come into play. Even the simplest custom functions sometimes suffer from the issue.
The problem usually goes away if you clear the formula cell and undo, or slightly edit the custom function's parameters to cause it to get re-evaluated. But that does not solve the issue. Google has been dragging their feet solving the underlying cause for many years.
To help the issue get Google's attention, star issue 233124478 in the issue tracker. Click the star icon ☆ in the top left-hand corner to vote for fixing the issue and get notified of status changes. Please do not post a "me too" or "+1" reply, but just click the star icon. Google prioritizes issues with the most stars.
Add-ons
I had two add-ons, and no function was loading.
I removed them, and all is well!
For me, renaming the custom function solved the problem. For now at least.
Just to add to Azmo 's answer...
I in fact removed all trailing semi-colons from the code:
// check if an item can be checked off
function checkedOff( need, have ) {
var retStr = "nope"
if( have >= need ){
retStr = "yep"
}
return retStr
}
And discovered, that when doing this over a large range you can also max out the acceptable number of calls to the API.
To get around it I added an IF THEN check around my custom script call.
So instead of:
=checkedOff(H10,H11)
Use something like this to check for a populated field before execution:
=if(H17<>"-",checkedOff(H10,H11),0)
My app script pulling data from my MSSQL database displayed just fine on GoogleSheets my laptop browser but then did not display on the Android GS app.
Per this thread it looks like there's a number of issues that could cause this, but #DestinyArchitect's answer above re: Permissions seemed like the simplest fix.
While testing my app script, Sharing was off for this GoogleSheet file.
Once I moved it to my team's folder where we have default Sharing switched on with a few team members, the MSSQL data showed right up on the GoogleSheet in my Android GS app.
Easy fix, this time...
In my case, the cell was stuck with a Loading... message due to "probably" a race condition between functions and formulas resolutions.
This is my custom function:
function ifBlank(value1, value2) {
return !!value1 ? value1 : value2;
}
This is the formula calling it:
=IFBLANK(VLOOKUP($A2,Overrides!$A$2:$E,5,FALSE),VLOOKUP($A2,'_resourceReq'!$A$2:$C,3))
Those VLOOKUP values could be pretty complex and could also take some time to resolve.
Solution: (in my case)
Wrapping the VLOOKUP() into TO_TEXT() or VALUE() for example.
So, changing the formula to =IFBLANK(TO_TEXT(VLOOKUP($A2,Overrides!$A$2:$E,5,FALSE)),TO_TEXT(VLOOKUP($A2,'_resourceReq'!$A$2:$C,3))) worked well.
If that doesn't work maybe try resolving the value from a function into a cell before using it as the argument of your custom function.
In my case, multiple cells using functions experienced this issue, but the simple answer was... wait.
In my case, I was scraping data via importXML functions across multiple rows and
columns. I was thrilled with the results, feeling on top of the world, then "Loading..." started showing its ugly face. For way too long. That's how I wound up here in troubleshooting mode, impatient and upset that Google was doing me wrong.
I tried many of the solutions here, only to find my "Loading..." antagonist acting unpredictably, popping up randomly like whacamoles, nothing to do with the code itself.
So. In my case, it was a matter of waiting it out (towards an hour for some rows, but I had so many cells fetching url data).
My layman's guess is that fetching data like this gets put in their bandwidth pipeline, lesser priority than typing a url into a search bar or other user requests.

Google places details API call return NOT_FOUND for an existing autocomplete reference

I have a problem maybe someone had the same issue.
I am calling google places autocomplete api call.
Then i am presenting the user with the results and he can select the place.
Base on the selection i am making places details call and retrieve the details of the place.
My problem is that some cases the details service return NOT_FOUND. the full response looks something like this
{\n \"debug_info\" : [],\n \"html_attributions\" : [],\n \"status\"
: \"NOT_FOUND\"\n}\n
Based on google api documentation, NOT_FOUND for place details is:
NOT_FOUND indicates that the referenced location was not found in the Places database.
But i got this Reference just 1 sec ago from autocomplete service call!
Anyone has the same problem?
Thanks,
Noam
There are two indexes here, one for the autocomplete suggest and one for the map details. You are seeing the results of the two indexes being updated at different times. If you supply the address in question, I can confirm with the appropriate teams, or you can just wait a couple of days for the indexes to come back into sync.
It could also be due to the fact that the business is closed.
https://developers.google.com/maps/documentation/places/web-service/search-find-place#id-errors
I had a similar issue when using the Find Place endpoint. I would get a successful response and a place_id returned and then calling the Details endpoint would return a NOT_FOUND error.
After adding business_status to the fields on my initial request to the FindPlace endpoint would return:
GET https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=gtdc.org&inputtype=textquery&languagecode=en&fields=place_id,business_status&key={{googlePlacesApiKey}}&locationbias=circle:{{radius}}#{{latitude}},{{longitude}}
Response:
{
"candidates": [
{
"business_status": "CLOSED_PERMANENTLY",
"place_id": "ChIJ7buuHhrhwogR_eWFgXkNyjY"
}
],
"status": "OK"
}
Essentially you just have to ignore any results where the status is CLOSED_PERMANENTLY as these will not work on the details endpoint.
Unfortunately there doesn't seem to be any way of returning the business_status on the Autocomplete endpoint but might be the same issue you are seeing.