'Add image from Drive folder to Form question

I'm using the Google script API for the first time to create a form with multiple similar questions in an automatic way. Basically, I'd like to loop through all images in a Drive folder and generate a dropdown list with an image as the following:

enter image description here

So far I managed to create this script:

function deployForm() {
  var form = FormApp.create('Classificação de Dígitos')

  var folder = DriveApp.getFoldersByName('mnist').next()
  var files = folder.getFiles()
  while ( files.hasNext() ) {
    Logger.log(files.next().getName())
    var img = DriveApp.getFileById(files.next().getId());
    form.addImageItem()
    .setImage(img)
    .setWidth(100)
    .setTitle('Como você classifica a seguinte imagem?')

    form.addListItem()
    .setRequired(true)
    .setChoiceValues(['Dígito 0',
                      'Dígito 1',
                      'Dígito 2',
                      'Dígito 3',
                      'Dígito 4',
                      'Dígito 5',
                      'Dígito 6',
                      'Dígito 7',
                      'Dígito 8',
                      'Dígito 9',
                      'Não sei dizer.'
                     ])
    form.addPageBreakItem()

    break;
  }

Which results in the following:

enter image description here

However, I did not figure it out how to insert an image to obtain something similar to the figure above. I'm aware that there is an addImageItem function but inspect the manual way of creating a form, it seems to me that the image should be "attached" to the dropdown menu, and not created as another item.

Also, the files seem to not be shown in the correct order (ordered as I see in Google Drive):

enter image description here

Log: [19-02-13 13:35:42:165 ART] data_47.png



Solution 1:[1]

On December 7, 2021, Google Forms API has been available in open beta. By this, I could confirm that this question got to be able to be resolved. In this answer, I would like to propose an answer using Google Forms API for resolving your goal.

In the current stage, Google Forms API can be used as the open beta by accessing at the Early Adopter Program page. Ref But, I believe that in the near future (The API is currently in Open Beta, and we anticipate promoting the API to GA in 2022.), this will be released as the alpha version.

The flow for using this sample script is as follows.

Usage:

1. Join Early Adopter Program.

In the current stage, in order to use Google Forms API beta, please join Early Adopter Program. Ref

When Google Forms API is released as the alpha version, this process can be skipped.

2. Link Google Cloud Platform Project to Google Apps Script Project.

In the current stage, Google Forms API cannot be used with Advanced Google services. So please link Google Cloud Platform Project to Google Apps Script Project. Ref And also, please enable Google Forms API at API console.

Also, I believe Google Forms API might be able to be used with Advanced Google services. At that time, this process can be skipped. At that time, please enable Forms API at Advanced Google services.

3. Scopes

In this sample script, the scope of https://www.googleapis.com/auth/forms.body is used for using Google Forms API. And, DriveApp uses the scope of https://www.googleapis.com/auth/drive, and UrlFetchApp uses https://www.googleapis.com/auth/script.external_request.

When Google Forms API could be used with Advanced Google services, I think that the scope of https://www.googleapis.com/auth/script.external_request not required to be used for using Forms API.

4. Sample script.

When your script is modified for achieving your goal, it becomes as follows. Please copy and paste the script editor of Google Apps Script lining with Google Cloud Platform Project.

This script also uses Drive API. So please enable Drive API at Advanced Google services before you use this script.

function myFunction() {
  var form = FormApp.create('Classificação de Dígitos');
  var url = `https://forms.googleapis.com/v1beta/forms/${form.getId()}:batchUpdate`;
  var folderId = DriveApp.getFoldersByName('mnist').next().getId();
  var { items } = Drive.Files.list({ q: `'${folderId}' in parents and trashed=false and mimeType='${MimeType.PNG}'`, maxResults: 1000, orderBy: "title", fields: "items(id,title)" });
  // console.log(items) // You can see the order of file list here.
  var requests = items.flatMap(({ id }, i) => [
    { createItem: { item: { pageBreakItem: {} }, location: { index: 1 } } },
    { createItem: { item: { title: 'Como você classifica a seguinte imagem?', questionItem: { question: { choiceQuestion: { type: "DROP_DOWN", options: ['Dígito 0', 'Dígito 1', 'Dígito 2', 'Dígito 3', 'Dígito 4', 'Dígito 5', 'Dígito 6', 'Dígito 7', 'Dígito 8', 'Dígito 9', 'Não sei dizer.'].map(e => ({ value: e })) } }, image: { altText: "sample", sourceUri: Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink.replace("=s220", "=s500") } } }, location: { index: 0 } } },
  ]);
  var res = UrlFetchApp.fetch(url, {
    method: "post",
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
    contentType: "application/json",
    payload: JSON.stringify({ requests: requests.reverse() })
  });
}
  • In this sample script, a new Google Form is created by FormApp.create, and then, the question is added by "Method: forms.batchUpdate".

  • And also, the image files are retrieved in the ascending order of the filename. But, in this case, from your question, it supposes that the filenames are like date_0.png, data_1.png,,,. Please be careful this.

5. Testing.

When the above script is run, a new Google Form is created including questions as the following image. The left and right images are on the 1st page and 2nd page, respectively.

enter image description here

Note:

  • When I posted this report, Google Forms API is the beta version. So the endpoint is like https://forms.googleapis.com/v1beta/forms/. When Forms API is released as the alpha version (version 1), I think that it will be like https://forms.googleapis.com/v1/forms/. At that time, about the detailed information, please check the official document. Ref And also, I think that when Google Forms API got to be able to be used with Advanced Google services, the endpoint is included in the internal server side.

References:

Updated at March 16, 2022:

Google Forms API has published a stable as the generally-available v1. Ref

In the current stage, the endpoint changed from https://forms.googleapis.com/v1beta/forms/ to https://forms.googleapis.com/v1/forms/. And, you can also use Forms API without joining to "Early Adopter Program".

But, as an important point, in order to use Forms API, it is required to link Google Cloud Platform Project to Google Apps Script Project. In the current stage, Google Forms API cannot be used with Advanced Google services. So please link Google Cloud Platform Project to Google Apps Script Project. Ref And also, please enable Google Forms API at API console. Ref

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1