How to show in Google Form value from Google Spreadsheet - google-apps-script

I have connected Google Spreadsheet with Google Form but I don't know, how can I include values from Spreadsheet to Form and display them (which will be in my scenario free left space for course registration).
explanation picture: https://drive.google.com/file/d/0B4HOotJEv18lLTNiY3ZmcGl3T3M/view?usp=sharing
Expected outcome: course has 30 free seats for students and I want to show in my Google Form, how many free seats lefts for course registration.
Many thanks for your help, also script example will be very welcome.

You can create the form in AppScript with Forms Service and set the questions and choices in the script. Within the script you can also reference a Spreadsheet, so you should be able to read the data from a spreadsheet and put it onto a form that way.
Haven't actually tried it, but it'd probably look something like:
var form = FormApp.create('New Form');
var item = form.addCheckboxItem();
var ss = SpreadsheetApp.openById("<ID>");
var val = ss.getRange(<RANGE>).getValue();
item.setTitle('Question ' + val + ' Question');
item.setChoices([
item.createChoice('ONE'),
item.createChoice('TWO'),
item.createChoice('THREE')
]);
You can also check out this Quickstart and Video.

Related

Dynamically Edit Multiple Choice Questions in Live Google Form with App Script

I am a teacher trying to create a registration system with Google Forms, Sheets, and App Script. I have tried using THIS THREAD to figure out the App Script I need to automatically update choices based on form submissions.
The Google Form will include class choices for Block 1, Block 2, Block 3, etc. Students will choose a class for each block and then submit the form. The Apps Script will look at the response spreadsheet, see that Class 1 for Block 1 is full, then removes it from the list of possible choices. The next student goes to register, and their only option is Class 2.
Based on the linked thread (see above), I tried this code. It seemed to work for one question... or so I thought. I linked my Spreadsheet here and include the Code Snippet.
Link to Spreadsheet -- Available Classes in "formMaker" Sheet. (if there's a better way to do this, please let me know)
Code:
function updateForm(){
var form = FormApp.openById('1Mrh79XlB_EX6jkK_dOX9sVIwAxTImqS8X2dIfEE0Juw'); // Base form
// need to read what dates are available and which are taken
var doc = SpreadsheetApp.getActiveSpreadsheet();
var dates = doc.getRange("FormMaker!A2:A").getValues(); //available options
var taken_dates = doc.getRange("Form Responses 6!C2:C").getValues();
// joining the taken dates into one string instead of an array to compare easier
var taken_dates_string = taken_dates.join("|");
var choice = [];
// loop through our available dates
for (d in dates){
}
var formItems = form.getItems(FormApp.ItemType.LIST); // our form list items
// assumption that first select list is the one you want to change
// and we just rewrite all the options to ones that are free
formItems[0].asListItem().setChoiceValues(choice);
}

How do I pull sec.gov interactive EDGAR data into google sheets?

I am trying to pull data from Sec.gov's EDGAR system for specific financial statements of specific filings for specific companies.
The first problem I am having in doing this is trying to figure out how to generally pull data from, for example, this link into a table in google sheets: https://www.sec.gov/cgi-bin/viewer?action=view&cik=320193&accession_number=0000320193-20-000096&xbrl_type=v#
The second problem I am having is trying to pull such data, but from specific financial statements (like the statements of cash flows) in the "financial statements" section, as the link above only brings me to the cover page of the filing, and each separate tab does not have separate links.
I am new at scripting within google sheets and am struggling to even find how to start at such a script that can do the above. This script I found on reddit (https://www.reddit.com/r/googlesheets/comments/bbousq/help_with_a_script_that_fetches_data_from_secgov/) is the closest script I have found online for what I am trying to do; however, I am unable to make it work and I am unsure how to do so:
function secData(company, tablenum) {if (!company)
company = 'TROV';
var url = "https://www.sec.gov/cgi-bin/browse-edgar?CIK=" + company + "&owner=exclude&action=getcompany";
var result = UrlFetchApp.fetch(url).getContentText();
var reg = /<a href="\/cgi-bin\/viewer.+?cik=(\d+).+accession_number=([\d|-]+)/.exec(result);
var cik = reg[1];
var accession = reg[2];
return 'https://www.sec.gov/Archives/edgar/data/' + cik + '/' + accession.replace(/-/g, '') + '/R'+tablenum+'.htm';
}
Which uses this formula in the sheet itself:
=IF(NOT(ISBLANK(G1)), importhtml(secData(G1,4),"table",1), "")
Where:
company = company name/ticker
tablenum = number of financial statement table (3 might = balance sheet)
Overall, I am wondering how to pull sec.gov interactive EDGAR data into google sheets and am hoping someone can help me do so?
You have an Excel document link on every page. You download that and convert it to Sheets, it's fairly easy. Here's a snippet to get you started.

dynamic values in websites and docs

Let's say my company has a website and it includes various text. One of the texts it includes is the name of my Director of HR. His/her name could appear 20 or 30 times in various pages and documents on our website. And, should there be a change and I hire a new Director of HR, someone'd have to do manually change those 20 or 30 values.
There's got to be a better way to do that. One option is a scrub the website of personal data in all instances but one, "Contact the Director of HR," and then have the one value "the director of HR is..." and hyperlink all the instances of the Director of HR to the Staff page. But I'm interested in dynamic values.
To begin with, let's say I have this Google Doc and this Google Sheet. How would I get the value on the Google Doc to change when I change the value on the Google Sheet?
You can generate a Doc from a Sheet using apps script.
You'll go to Tools -> Script Editor in your Sheet.
Every time you run this script it will generate a new Doc with the value present in your sheet.
function myFunction() {
var doc = DocumentApp.create('HR Sheet');
var data = SpreadsheetApp.getActive().getDataRange().getValues()
var body = doc.getBody();
body.appendParagraph(data[1][1]);
}
If you run this script it will generate a new sheet and put the name of the HR Director on the sheet.
Helpful Link:
Google Docs documentation with scripting
You want to do the following:
Get a list of ROLES and NAMES from a Sheet.
For each ROLE/NAME pair, look for a specific value in a Google Doc, and replace that value with the corresponding NAME.
You can use replaceText(searchPattern, replacement) to achieve this. It could be something like this:
function findAndReplace() {
// Get "Sheet1", where data is:
var sheet = SpreadsheetApp.openById("your-spreadsheet-id").getSheetByName("Sheet1");
// Get the document body:
var doc = DocumentApp.openById("your-doc-id").getBody();
// Get the "ROLE/NAME" values:
var values = sheet.getRange(2, 1, sheet.getLastRow() - 1, 2).getValues();
// For each "ROLE/NAME" pair, replace text:
values.forEach(row => body.replaceText("{{" + row[0] + "}}", row[1]));
}
Note:
In this sample, the values to look for in the Doc are built using each corresponding role, with this pattern: {{your-role-name}}. [ is a special character for regex, so I think using {{ is more appropriate for this situation.
Reference:
Body.replaceText(searchPattern, replacement)
These answers were great re: Google Docs (which was the question I asked). But re: Website, I found this really useful plugin, TablePress, and the extension, Single Cell Content Shortcode. Populating my Director of HR in a Wordpress Page is as easy as using the shortcode [table-cell id=1 cell=C3 /].
I'm playing with autorefresh now, which'd repopulate the uploaded Sheet from the URL regularly, so I couldn't have to reupload the Google Sheet every time.
Looks like it'll work 100% for my purposes of populating Google Sheet values on Wordpress pages.

Is there a way to auto save data in google sheet?

Is there a way to auto save data entered in a temp area (risk is a calculated value based on the values entered) on google sheet. I have a working space and all my logs is now needing to be saved for later review.
see sample sheet.
Created a sample data screenshot
Thanks
There's two ways to do it. You'll need to create a log of sorts and have the dashboard reference the bottom most entry. If you have App Script experience, that would be the better solution, however without it you could use the a Google Form for editing the dashboard. There wouldn't be any formulas alone that will work for this due to needing to hardcode the inputs, and formulas can only return values as arrays (mirror/change values in other cells).
You can use a Google Form that is linked to the spreadsheet so that someone has to submit the form with the inputs to change the dashboard. You would then use a =Max() function on the timestamp column, and then either Vlookup or Index(match()) to return the variables for the dashboard based off Max(timestamp).
The alternative method would be to create basically set of cells similar to the input table, and add a button that if clicked, takes, the values and updates them in the variables for the dashboard, but also logs them on another sheet. (It would be something like this)
Thank you all for the suggestions. I end up using the below script to accomplish the task.
function FormExec() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sinput = ss.getSheetByName("sheet1");
var soutput = ss.getSheetByName("sheet2");
var input = sinput.getRange(14, 3, 15).getValues();
var flatin = [].concat.apply([], input);
soutput.getRange(soutput.getLastRow()+1, 1,1, 15).setValues([flatin]);
soutput.insertRowAfter(soutput.getLastRow());
Logger.log(input);
}

Dynamically edit multiple choice options in live Google Form using Apps Script

I'm a high school teacher in L.A. trying to create a course registration system using Apps Script. I need the Google Form I'm using for this registration to:
Question 1) Update the choices available in subsequent multiple choice questions on new pages based on a student's current response choices.
Question 2) Eliminate choices from the form when a multiple choice option has reached it's "cap".
Question 1 Example)
A student registers for “tie-tying” in workshop 1, and gets taken to a new page. The Script edits the available choices on that new page based on the student’s first choice, and removes “tie-tying” from the list of possible choices on that new page, so “etiquette” is their only remaining option.
Question 2 Example)
Students can either register for “tie-tying” or “etiquette”, both responses are initially available in the Google Form. 30 students take the survey, all 30 register for the “tie-tying” workshop. The Apps Script references the response spreadsheet, realizes the “tie-tying” workshop is full, then removes it from the Google Form's list of possible choices. Student 31 goes to register, and their only option is “etiquette”.
If my question has already been asked and answered (believe me, I did search!) I'd appreciate the redirection.
I believe we can achieve your second objective without too much difficulty and modify the form, based on the current state of response.
The approach is to
Create the form and associate it with a response spreadsheet
In that response spreadsheet, create a script with a function (updateForm for instance)
Bind that function with the onFormSubmit event, see Using Container-Specific Installable Triggers.
Analyse the response in the updateForm function and modify your form using the Form Service
For instance
function updateForm(e) {
if (e.values[1] == 'Yes') {
Logger.log('Yes');
var existingForm = FormApp.openById('1jYHXD0TBYoKoRUI1mhY4j....yLWGE2vAm_Ux7Twk61c');
Logger.log(existingForm);
var item = existingForm.addMultipleChoiceItem();
item.setTitle('Do you prefer cats or dogs?')
.setChoices([
item.createChoice('Cats'),
item.createChoice('Dogs')
])
.showOtherOption(true);
}
}
When it comes to achieving the goal in your first question, its more delicate, as the form will not submit mid way. What is possible is to go to different pages based on different responses to a Multiple Choice question, your use case may fit this method, although its not very dynamic.
Further its possible to use html Service to create completely dynamic experience.
Let me know if you need further information.
You are not able to create this type of dynamic form using the Google Forms Service, because there is no interaction between the service and scripts during form entry, except upon Form Submission. In the case of a multi-page form, a script has no way to know that a student has completed one page and gone on to another.
You could achieve this using the HtmlService or UiService, though. In either case, you'd rely on the client-side form interacting through server-side scripts to get updated lists of course options, then modifying the next 'page'. It will be complex.
The other answer to this question will keep adding a multichoice select each time for the form is submitted. Using similar approach of:
Create the form and associate it with a response spreadsheet
In that response spreadsheet, create a script with a function (updateForm for instance)
Bind that function with the onFormSubmit event, see Using Container-Specific Installable Triggers.
Analyse the response in the updateForm function and modify your form using the Form Service
I've used the following code to modify a list select which could be easiliy modified for a multiple choice.
function updateForm(){
var form = FormApp.openById('YOUR_FORM_ID'); // Base form
// need to read what dates are available and which are taken
var doc = SpreadsheetApp.getActiveSpreadsheet();
var dates = doc.getRange("dates!A1:A10").getValues(); //available options
var taken_dates = doc.getRange("responses!F2:F51").getValues(); //just getting first 50 responses
// joining the taken dates into one string instead of an array to compare easier
var taken_dates_string = taken_dates.join("|");
var choice = [];
// loop through our available dates
for (d in dates){
// test if date still available
if (dates[d][0] != "" && taken_dates_string.indexOf(dates[d][0]) === -1){
choice.push(dates[d][0]); // if so we add to temp array
}
}
var formItems = form.getItems(FormApp.ItemType.LIST); // our form list items
// assumption that first select list is the one you want to change
// and we just rewrite all the options to ones that are free
formItems[0].asListItem().setChoiceValues(choice);
}