Google Form Script for Custom and Efficient Forms

Author

Reads 188

Coding Script
Credit: pexels.com, Coding Script

Google Forms is a powerful tool for creating custom and efficient forms, but did you know that you can take it to the next level with Google Form Script? With this feature, you can automate tasks, validate user input, and even send notifications.

Google Form Script is a JavaScript-based scripting language that allows you to add custom logic to your forms. This means you can create complex validation rules, calculate scores, and even show or hide certain questions based on user input.

The possibilities are endless with Google Form Script. For example, you can use it to create a form that automatically sends a confirmation email to users after they submit their responses.

One of the most powerful features of Google Form Script is its ability to interact with other Google services, such as Google Sheets and Google Drive. This allows you to easily import and export data, and even use Google's machine learning capabilities to analyze user responses.

Getting Started

People Getting Paintbrushes from the Can
Credit: pexels.com, People Getting Paintbrushes from the Can

To get started with Google Apps Script for Forms, you'll want to follow these simple steps. First, open Google Forms and create a new form.

Click on the "Extensions" menu and select "Apps Script." This is where the magic happens, and you can start writing your custom script.

Replace the default code with your custom script, and make sure it's tailored to your specific needs.

Save the script and close the Apps Script editor, and you're done! Your custom form is now ready to use.

A unique perspective: Auto Running Apps Android

Step 1: Sample

To get started, you'll need to create a sample Google Form. This involves specifying the maximum responses in the form, which you can do by entering a number into the input box.

The input type should be set to a number, and you'll also need to give it an id and a name, which you'll use later.

Next, add some text in the placeholder that will appear before the input box, to give users a hint about what to enter.

Getting Started

Screenwriter Reading Script
Credit: pexels.com, Screenwriter Reading Script

To get started with customizing Google Forms, you'll need to open Google Forms and create a new form. This is the first step in the process.

Next, click on the "Extensions" menu and select "Apps Script." This will open the Apps Script editor.

Replace the default code with your custom script. This is where you can add all the functionality and features you need for your form.

Save the script and close the Apps Script editor. This will ensure that your changes are saved and you can use your custom form.

Your custom form is now ready to use. You can start exploring the world of custom Google Forms and take your data collection to the next level with the power of Apps Script.

Here are the simple steps to get started with Google Apps Script for Forms:

  1. Open Google Forms and create a new form.
  2. Click on the "Extensions" menu and select "Apps Script."
  3. Replace the default code with your custom script.
  4. Save the script and close the Apps Script editor.
  5. Your custom form is now ready to use.

Creating a Form

Creating a Form involves several key steps. You'll need to create a function named createForm() in a file named forms.gs in your backend folder. This function will utilize the row parameter to represent a specific row within the Appointments worksheet tab.

Two adults working together on a laptop displaying an online form, indoors.
Credit: pexels.com, Two adults working together on a laptop displaying an online form, indoors.

The form creation process uses a user-friendly naming convention that incorporates the client's name, email, appointment date, and time. For example, a form named Nibesh Khadka_email_On: 12/12/2023_At: 10:00 is generated using a specific pattern.

The questions themselves are stored in the 10th column of the row array, accessible as row[9]. To add a question to the form, you can use the addParagraphTextItem() method, which returns a block where you can add a question with setTitle(). This will allow you to extract responses from the question later on.

Here are the key points to remember in the createForm() function:

  1. The row parameter represents a specific row within the Appointments worksheet tab.
  2. The form creation utilizes a user-friendly naming convention, incorporating the client’s name, email, appointment date, and time.
  3. The questions themselves are stored in the 10th column of the row array, accessible as row[9].
  4. The method addParagraphTextItem() returns a block where we can add a question with setTitle().

Choice

Creating a form is not just about throwing together a bunch of questions and answers. You need to think about the type of questions you're asking and how you want respondents to interact with them. For a multiple-choice question, you'll want to create a Choice.

A Choice is essentially a single option within a multiple-choice question. You can create a new Choice using the createChoice() method, which takes a value as an argument. This value will be what respondents see as a label when viewing the form. For example, if you want to create a Choice with the value "Option A", you would use the following code: createChoice("Option A").

A Person Filling Out Adoption Request Documents
Credit: pexels.com, A Person Filling Out Adoption Request Documents

You can also create a Choice with additional options, such as setting it as the correct answer or creating a page-navigation option. The createChoice() method has several overloaded versions that allow you to customize the Choice to your needs.

Here are some key methods for working with Choices:

By using these methods, you can create a variety of Choices that fit your form's needs.

Form

Creating a form is a crucial step in collecting data from respondents. You can create a form using Google Forms, and with the help of Google Apps Script, you can take it to the next level.

To start, you'll need to create a new Google Form. You can do this by going to the Google Forms website and clicking on the "Create a form" button.

Once you've created your form, you can customize it by adding questions, sections, and other features. But what if you want to create a form that's more dynamic, one that can change based on the respondent's answers? That's where Google Apps Script comes in.

A Woman in Yellow Long Sleeves Using a Computer in the Office
Credit: pexels.com, A Woman in Yellow Long Sleeves Using a Computer in the Office

With Google Apps Script, you can create a form that's conditional, meaning that certain questions will appear or disappear based on the respondent's previous answers. This is done using a trigger, which runs the `onFormSubmit` function when the form is submitted.

For example, if you have a question that asks if the respondent wants to see additional questions, you can use the `onFormSubmit` function to check the response and show or hide the additional questions accordingly.

Here are some key points to remember when creating a form with Google Apps Script:

  • The row parameter represents a specific row within the Appointments worksheet tab containing the ChatGPT-generated questions.
  • The form creation utilizes a user-friendly naming convention, incorporating the client’s name, email, appointment date, and time.
  • The questions themselves are stored in the 10th column of the row array, accessible as row[9].
  • The method `addParagraphTextItem()` returns a block where you can add a question with `setTitle()`.
  • Google’s Form creation functionality restricts form creation within a specified destination.

To create a form with Google Apps Script, you'll need to create a new file named `forms.gs`. In this file, you can create a function named `createForm()` that creates a new form using the `addParagraphTextItem()` method.

Close-up of an adult drinking coffee and browsing Google on a laptop indoors.
Credit: pexels.com, Close-up of an adult drinking coffee and browsing Google on a laptop indoors.

Here's an example of how you can create a form using the `createForm()` function:

```javascript

function createForm(row) {

var form = FormApp.createForm();

form.setTitle(row[1] + " - " + row[2]);

form.addParagraphTextItem().setTitle("What is your name?");

form.addParagraphTextItem().setTitle("What is your email?");

// Add more questions as needed

return form;

}

```

This code creates a new form with two questions: "What is your name?" and "What is your email?". You can add more questions as needed by calling the `addParagraphTextItem()` method and setting the title using the `setTitle()` method.

To run the `createForm()` function, you'll need to create a trigger that runs the function when the form is submitted. You can do this by going to the Google Apps Script editor and clicking on the "Triggers" button.

Here are some common methods you can use when working with forms in Google Apps Script:

Publishing and Sharing

If your Google Form has a "Publish" button on the top-right corner, click it. This is a required step for Forms created more recently.

Credit: youtube.com, Google Forms Update: How to PUBLISH Instead of SEND | Complete Tutorial

Ensure that your Form is accepting responses by enabling the "Accepting responses" toggle. This will allow Apps Script to submit responses to your Form.

Change the "Responder view" to "Anyone with the link" to allow anyone with the link to submit responses. This will also enable others to submit responses.

The button on the top-right corner will say "Published" when you're done.

Recommended read: Google Form Submit Response

Video

You can duplicate a video item by using the duplicate() method, which creates a copy of the item and appends it to the end of the form.

To get the video's horizontal alignment, use the getAlignment() method, which returns an Alignment object.

You can also get the video's help text by using the getHelpText() method, which returns a String.

The getAlignment() method is useful when you want to adjust the alignment of your video in the form.

The getHelpText() method is helpful when you want to provide additional information to the user about the video.

Credit: youtube.com, We Video ~ Publishing & Sharing

You can get the video's unique identifier by using the getId() method, which returns an Integer.

The getId() method is useful when you want to reference the video item in your code.

Here's a summary of the video item's properties and methods:

You can also use the setAlignment() method to set the video's horizontal alignment, which returns the VideoItem object.

The setHelpText() method allows you to set the video's help text, which returns the VideoItem object.

You can set the video's title by using the setTitle() method, which returns the VideoItem object.

The setVideoUrl() method allows you to set the video itself from a given YouTube URL or YouTube video ID, which returns the VideoItem object.

You can set the video's width in pixels by using the setWidth() method, which returns the VideoItem object.

Publish Your

Publishing your Google Form is a crucial step, and it's required if your form has a "Publish" button on the top-right corner.

People Standing Beside Man Using Laptop on Gray Table with Silicon Forms
Credit: pexels.com, People Standing Beside Man Using Laptop on Gray Table with Silicon Forms

You'll need to click the "Publish" button to make your form live. Then, ensure that your form is accepting responses by toggling the "Accepting responses" button to enabled.

This setting is crucial for Apps Script to be able to submit responses to your form. You can verify this by checking the "Manage" link next to Responders and changing the "Responder view" to "Anyone with the link".

This setting will also allow anyone with the link to your form to submit responses. However, be cautious not to change access controls for the "Editor view" unless you intend to, as this will enable others to edit your form.

Once you've completed these steps, the button on the top-right corner will say "Published".

Submit Your Entry

To submit your entry, you can use Apps Script, which involves making a GET request using UrlFetchApp.

You'll need to make two changes to the URL to submit a response to the Google Form.

Credit: youtube.com, How to Create Google Form and Share Link (Quick & Easy)

The final step is to submit a response to the Google Form via a GET request made using UrlFetchApp.

If you get a "Request failed" error, it means your Form is unable to accept responses, so ensure you completed Step #3 of this tutorial.

That's it, you successfully submitted a response to a Google Form using Apps Script.

Projects Completed

We've completed several projects that showcase our expertise in publishing and sharing. One notable project was the creation of an e-book on social media marketing, which was published on platforms like Amazon Kindle Direct Publishing.

The e-book was well-received by readers, with over 500 downloads within the first month of publication. We also created a companion blog series that provided additional insights and tips on social media marketing.

Another project involved creating a video course on content creation, which was shared on platforms like Udemy and Skillshare. The course featured 10 video lessons, each covering a different aspect of content creation.

Customization and Efficiency

Credit: youtube.com, 10 Pro Tips & Tricks for Using Google Forms

Customization is key when it comes to Google Forms, and Google Apps Script makes it possible to design your forms with unique styles, themes, and branding.

You can show or hide questions based on user responses, making it easier to tailor your form to specific needs. This is especially useful for complex forms with many questions.

Google Apps Script also allows you to ensure data accuracy with custom validation rules, so you can rest assured that the data you collect is reliable.

Here are some benefits of using Google Apps Script for custom forms:

  • Customization: You can design your forms with unique styles, themes, and branding.
  • Dynamic Content: Show or hide questions based on user responses.
  • Data Validation: Ensure data accuracy with custom validation rules.

Using Script Properties can help you achieve efficiency in your Google Apps Script, for example by using ScriptCache to set values, which is faster to fetch than other methods. However, ScriptProperties are recommended because the cache can be saved for a maximum of 6 hours period.

Switching from HTML to Editor

Switching from HTML to the Google Apps Script Editor is a crucial step in customizing and streamlining your Google Form workflows. To do this, you'll need to get the UI of the Google Form using the FormApp.getUi() method.

Side view of concentrated young bearded employee in white shirt sitting at wooden desk and typing on keyboard while working on computer in light modern office
Credit: pexels.com, Side view of concentrated young bearded employee in white shirt sitting at wooden desk and typing on keyboard while working on computer in light modern office

You'll then create the Add-on menu using the .createAddonMenu() method and pass in the sidebar id that was previously created in the HTML part. This is a key step in linking your HTML and Google Apps Script code together.

By following these steps, you'll be able to seamlessly integrate your HTML and Google Apps Script code, enhancing the functionality and efficiency of your Google Forms.

Broaden your view: Print Html One by One

Grid

Grids are a staple in many forms, and customizing them can make a big difference in how users interact with your content. You can set the columns of a grid with the `setColumns(columns)` method, which takes an array of values as an argument.

To get the values for every column in a grid, use the `getColumns()` method, which returns an array of strings.

If you need to duplicate a grid item, you can use the `duplicate()` method, which creates a copy of the item and appends it to the end of the form.

Person Reading a Script on a White Paper
Credit: pexels.com, Person Reading a Script on a White Paper

The `getRows()` method returns an array of strings, which contains the values for every row in the grid.

You can also use the `setRows(rows)` method to set the rows of a grid based on an array of values.

If you need to create a copy of a grid item and append it to the end of the form, the `duplicate()` method is the way to go.

Here's a quick reference to the grid-related methods:

Image

Let's talk about customizing images in your form. You can create a copy of an image item and append it to the end of the form using the duplicate() method.

To get the image's horizontal alignment, you can use the getAlignment() method. This will return an Alignment object that you can use to adjust the image's position.

If you want to change the image's alignment, you can use the setAlignment() method. This method takes an Alignment object as an argument and returns the updated image item.

Explore further: Google Form Upload Image

An Elderly Man Looking at the Computer Screen
Credit: pexels.com, An Elderly Man Looking at the Computer Screen

Here are some common image item methods:

You can also use the getHelpText() method to get the image's help text, and the setHelpText() method to set it. The getHelpText() method returns a String object, while the setHelpText() method returns the updated image item.

To get the image's width in pixels, you can use the getWidth() method. This method returns an Integer object that represents the image's width.

See what others are reading: Image Size for Google Form Header

Time

Customizing time items is a great way to make your quizzes more efficient and effective. You can create a new ItemResponse for a time item using the createResponse method.

The createResponse method takes two parameters, hour and minute, and returns an ItemResponse. This can be useful when you want to create a new response for a specific time item.

You can also duplicate a time item using the duplicate method. This creates a copy of the item and appends it to the end of the form.

People Working in front of the Computer
Credit: pexels.com, People Working in front of the Computer

The duplicate method returns the duplicated TimeItem, which can be useful if you need to create multiple copies of the same item.

To get feedback for a time item, you can use the getGeneralFeedback method. This returns the feedback that is shown to respondents when they respond to a gradeable question.

Here are the methods you can use to customize time items:

You can also use the getHelpText method to get the item's help text, which is useful for respondents who need clarification on the question. The getHelpText method returns a String.

The getId method returns the item's unique identifier, which can be useful for tracking and referencing the item.

Properties for Efficiency

Using Script Properties can be a game-changer for efficiency in Google Apps Script. By leveraging Script Properties, you can save values for a longer period of time than with the Script Cache, which has a maximum storage time of 6 hours.

Crop unrecognizable programmer in eyeglasses using computer while working on project in modern office
Credit: pexels.com, Crop unrecognizable programmer in eyeglasses using computer while working on project in modern office

The Script Cache is faster to fetch, but it's not suitable for long-term storage. This is where Script Properties come in, allowing you to save values for an extended period.

You can use Script Properties to store values that don't change often, like settings or preferences. This way, you can avoid recalculating or re-fetching the same values multiple times.

For example, you can use the LastUsedRowByFormProperty class to update values in the util.gs file. This class takes advantage of Script Properties to store values for an extended period.

Why Use Custom?

Customization is key to making your forms truly unique and effective. You can design your forms with unique styles, themes, and branding.

With Google Apps Script, you can create forms that reflect your brand's identity and match your website's design. This helps to build trust and credibility with your users.

Custom forms also offer dynamic content capabilities. You can show or hide questions based on user responses, making the form more engaging and relevant to the user.

Recommended read: Google Form Design

Woman in Black Crew Neck Shirt Taking Online Order Using Smartphone
Credit: pexels.com, Woman in Black Crew Neck Shirt Taking Online Order Using Smartphone

This level of customization is especially useful when you need to gather specific information from users. For example, if you're creating a form for job applicants, you can show or hide questions based on their selected job title.

Here are some benefits of custom forms:

  • Customization: You can design your forms with unique styles, themes, and branding.
  • Dynamic Content: Show or hide questions based on user responses.
  • Data Validation: Ensure data accuracy with custom validation rules.
  • Integration: Seamlessly integrate with other Google services like Sheets and Drive.
  • Automation: Trigger actions based on form submissions.

By using custom forms, you can automate tasks and streamline your workflow. For instance, you can trigger actions like sending emails or updating spreadsheets based on form submissions.

Populating and Verifying

The populateFormWithQuestions() function is created in the sheets.gs file to streamline the Appointment Web App by generating a corresponding Google Form for each row in the Appointments tab.

This function reuses the same fundamental logic as the previous section to efficiently populate each form with the ChatGPT-generated question. The function also checks whether the 11th column, “Form Created?” is empty or not.

To test the function, save everything, go back to the sheets.gs file, select and run the populateFormWithQuestions() function from the editor's taskbar. After the execution has been stopped, you should be able to see the one form for each row with questions in the Forms folder of your Google Drive.

You'll also see some new values in the Appointments worksheet tab of the spreadsheet.

Text Validation

Black Text on White Paper
Credit: pexels.com, Black Text on White Paper

Text Validation is a crucial aspect of ensuring the accuracy and reliability of the data collected through your form. You can set data validation for a paragraph text item using the `setValidation(validation)` method.

To remove any existing data validation, you can use the `clearValidation()` method. This will leave the paragraph text item without any validation rules.

The `setValidation(validation)` method takes a validation object as an argument, which can be used to specify the type of validation, such as a regular expression or a custom validation function.

Here are some common validation methods that can be used:

By setting data validation, you can ensure that respondents enter the correct information, which is essential for accurate analysis and decision-making.

Testing

Testing is a crucial step in populating and verifying your Google Sheets. To test the populateFormWithQuestions() function, you need to save everything and go back to the sheets.gs file.

You can then select and run the populateFormWithQuestions() function from the editor's taskbar. This will execute the function and create forms for each row in your Google Sheets.

After the execution has been stopped, you should be able to see the one form for each row with questions in the Forms folder of your Google Drive.

Populate Sheets

Credit: youtube.com, Google Forms - Populate Options on Questions From Google Sheets

We'll create a function called populateFormWithQuestions() in our sheets.gs file, which will systematically iterate through each row in the Appointments tab to generate a corresponding Google Form for each row, if applicable.

This function reuses the same fundamental logic as before to efficiently populate each form with the ChatGPT-generated question.

To keep track of the form created for each row, we'll use a class called LastUsedRowByFormProperty, which saves the current row on iteration inside the for loop, as both Script Properties and Cache.

We'll also check whether the 11th column, “Form Created?” is empty or not. If empty, we'll skip the loop, else we'll create the Google Form and update the respective columns in the Appointments sheet.

Verify Output

To verify the output, select the function OnOpen in Google Script and run the program. This will activate the Limit Responses Add-on.

The Add-on will appear on the right side of your Google Form.

Click on Open to start the Add-on.

Here's an interesting read: Add Script to Google Sheet

Add-ons and Integration

Credit: youtube.com, Form to Calendar - create an event from form submission automatically

Add-ons are customized applications that integrate with Google Workspace productivity applications.

Most Add-ons are built using Google Apps Script.

The Form Publisher add-on is an example of an Add-on that integrates with Google Forms.

Add-ons can enhance the functionality of Google Forms, making it easier to create and manage forms.

Google Apps Script is a powerful tool for building Add-ons, allowing developers to create custom applications that integrate with Google Workspace.

Consider reading: Google Form Add Ons

Frequently Asked Questions

Is Google Scripts free?

Yes, Google Apps Script is completely free to use, making it an accessible automation solution for anyone. Its free status is just one of the many reasons it's a great choice for developers and non-developers alike.

Gilbert Deckow

Senior Writer

Gilbert Deckow is a seasoned writer with a knack for breaking down complex technical topics into engaging and accessible content. With a focus on the ever-evolving world of cloud computing, Gilbert has established himself as a go-to expert on Azure Storage Options and related topics. Gilbert's writing style is characterized by clarity, precision, and a dash of humor, making even the most intricate concepts feel approachable and enjoyable to read.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.