Categories
Code

Add the Edit Response URL of the Google Form to Google Spreadsheet

This Google Apps Script code will insert the Form Edit Response URL to the Google Spreadsheet when a new Google Form is submitted. The response URL is added to the same spreadsheet that is collecting the responses for the Google Form.

The code is inserting the raw link here but you can use the built-in HYPERLINK() formula to create a clickable hyperlink inside the spreadsheet cell. The script function can also be integrated with the Google Shortener API (or Bitly) to insert a short URL that is easier to copy-paste and share.


/*
* Written by Amit Agarwal
* Web: digitalinspiration.com
* Email: amit@labnol.org
* MIT License 
*/

// Create the Form Submit Trigger
function createFormTrigger() {
  var triggerName = "addFormResponseUrl";
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  ScriptApp.newTrigger(triggerName)
    .forSpreadsheet(spreadsheet)
    .onFormSubmit()
    .create();
}

function addFormResponseUrl(e) {
  
  // Get the Google Form linked to the response
  var responseSheet = e.range.getSheet();
  var googleFormUrl = responseSheet.getFormUrl();
  var googleForm = FormApp.openByUrl(googleFormUrl);
  
  // Get the form response based on the timestamp
  var timestamp = new Date(e.namedValues.Timestamp[0]);
  var formResponse = googleForm.getResponses(timestamp).pop();
  
  // Get the Form response URL and add it to the Google Spreadsheet
  var responseUrl = formResponse.getEditResponseUrl();
  var row = e.range.getRow();
  var responseColumn = 10; // Column where the response URL is recorded.
  responseSheet.getRange(row, responseColumn).setValue(responseUrl);
}

Please note that anyone who has access to this unique Form Response Edit URL can change the form response. The getEditResponseUrl() method will return the URL to edit a response that has already been submitted, even if the Form.setAllowResponseEdits(enabled) setting is disabled.

Also, you should always get the URL of the linked Google Form via the active sheet and not the active spreadsheet as there could multiple forms associated with the same Google Spreadsheet.

Categories
Code

Send SMS with Google Forms

A teacher has created a Google Form where students enter their name, the course they’ve enrolled into and their parent’s mobile number. The requirement is that as soon as a student enrolls in a course, an automated SMS message should be sent to the parent’s cell phone.

This can be easily done with OnFormSubmit trigger in Google Apps Script and SMS API. We are using MSG91 for this example but you can use Twilio or any SMS service that offers an HTTP Rest API for sending text messages.

function createTriggers() {
  
  ScriptApp
  .getProjectTriggers()
  .forEach(function(trigger) {
    ScriptApp.deleteTrigger(trigger);
  });
  
  ScriptApp
  .newTrigger("triggerSMS")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onFormSubmit()
  .create();
  
}

function triggerSMS(e) {

  var response = e.namedValues;
  var message = response["Student Name"].toString() + " enrolled for " + response["Course"].toString();  
  var url="https://control.msg91.com/api/sendhttp.php";
  
  var payload = {
    "authkey" : "AUTH_KEY",
    "mobiles" : response["Mobile Number"].toString(),
    "message" : encodeURIComponent(message),
    "sender"  : "GFORMS",
    "route"   : 4
  };
  
  var options = {
    "method"  : "POST",
    "payload" : payload,   
    "followRedirects" : true,
    "muteHttpExceptions": true
  };
  
  UrlFetchApp.fetch(url, options);
  
}
Categories
Code

Post Google Forms Reponse into Insightly CRM

An organization uses Google Forms to capture leads and would like to automatically post the form submissions as open leads into Insightly for pursual by their sales team. This can be easily done with the help of Google Apps Script that gets triggered automatically on form submit.

Open the Google Form, go to Script Editor from the menu and paste the source code. You’ll need to use your own Insightly API key that can be found under “User Settings” (click the profile icon in the upper right corner of your Insightly dashboard).

/*

Google Forms to Insightly
=========================

Written by Amit Agarwal
Website: ctrlq.org
Email: amit@labol.org
Twitter: @labnol

*/

function setupTriggers() {

  var form = FormApp.getActiveForm();
  ScriptApp.newTrigger("ctrlqFormSubmit").forForm(form).onFormSubmit().create();

}

function ctrlqFormSubmit(e) {

  try {

    var i = 0,
      lead = {},
      items = e.response.getItemResponses();

    for (i = 0; i < items.length; i++) {

      var title = items[i].getItem().getTitle();
      var answer = items[i].getResponse().toString();

      switch (title) {
        case "Company Name":
          lead.ORGANIZATION_NAME = answer;
          break;
        case "First Name":
          lead.FIRST_NAME = answer;
          break;
        case "Last Name":
          lead.LAST_NAME = answer;
          break;
        case "Phone Number":
          lead.PHONE_NUMBER = answer;
          break;
        case "Email Address":
          lead.EMAIL_ADDRESS = answer;
          break;
      }
    }

    var key = "ctrlq-org";

    var response = UrlFetchApp.fetch(
      "https://api.insight.ly/v2.2/Leads", {
        method: "POST",
        payload: JSON.stringify(lead),
        headers: {
          'Authorization': 'Basic ' + Utilities.base64Encode(key),
          'Content-Type': 'application/json'
        }
      }
    );

    Logger.log(response.getContentText());

  } catch (error) {

    Logger.log(error.toString());

  }

}

The above Google Form uses standard contact us fields like name, email address and phone number that can be directly mapped to the standard lead in Insightly. If you have others questions in Google Forms, you can use the custom fields to map them into an Insightly lead. For support, email amit@labnol.org

Categories
Code

Create Trello Cards from a Google Form

Trello provides you a unique email address (like xyz@boards.trello.com) for any board in you account and any email message sent to this address is added as a new card to the Trello Board. @jezhou has written a Google Scripts that redirects Google Form submissions to a Trello using this email option.

When a Google Form is submitted, the onFormSubmit() event is triggered which then forwards the Google Form data to Trello via the GmailApp service. The subject is the title of the card while the email body goes in the description field. The script may be extended to forward Google Form entries to other services like WordPress, Evernote, Pocket, Tumblr, etc. since they too allow posting via Email.


// Credit: https://gist.github.com/jezhou/ac34cef8ce02aa051cfd/53a2b9605d99a13ebe090da5d4642be71b5e2e54

// Fire off this function in the script editor to enable.
function init() {

  var triggers = ScriptApp.getProjectTriggers();
  var form = FormApp.getActiveForm();
  
  // Delete all triggers before making a brand new one.
  for(var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }
  
  // Set up a new trigger
  ScriptApp.newTrigger('submitToTrello')
           .forForm(form)
           .onFormSubmit()
           .create();
  
  Logger.log('Successful creation of new submitToTrello trigger.');
  
}

function submitToTrello(e) {
  
  var form = FormApp.getActiveForm();
  var latestItemResponses = form.getResponses().pop().getItemResponses();
 
  if (MailApp.getRemainingDailyQuota() > 0) {
    
    // Trello email address goes here
    var email = "ctrlq@boards.trello.com";
    
    // Subject line will be the title of the event on Trello card
    var subject = latestItemResponses[3].getResponse();
    
    // Intial empty body
    var body = "";
    
    // Loop through recent responses and format them into string
    latestItemResponses.forEach(function (value, index, array) {
      var formatted = Utilities.formatString("**%s**\n %s\n\n", value.getItem().getTitle(), value.getResponse());
      body = body.concat(formatted);
    });
        
    MailApp.sendEmail(email, subject, body);
  }

}
Categories
Code

Post Google Forms Submissions to Slack

Andy Chase has published a Google Script that will let you automatically post Google Form submissions to a Slack channel. You need to place the script inside the script editor of your Google Forms editor and associate the onSubmit() method with the Form Submit trigger.

// replace this with your own Slack webhook URL
// https://crowdscores.slack.com/services
var webhookUrl = 'https://hooks.slack.com/services/****/****/****';

function onSubmit(e) {
  var response = e.response.getItemResponses();

  // Setup 2:
  // Modify the below to make the message you want. 
  // See: https://developers.google.com/apps-script/reference/forms/form-response
  var d = e.response.getRespondentEmail() + " | " + response[0].getResponse();

  var payload = {
    "payload": '{"text": "' + d + '"}'
  }

  var options = {
    "method": "post",
    "payload": payload
  };

  UrlFetchApp.fetch(webhookUrl, options);
};

Also see: Email Notifications for Google Forms