Formular oder Quiz aktualisieren

Wenn Sie einem Formular Inhalte hinzufügen oder die Einstellungen, Metadaten oder Inhalte aktualisieren möchten, verwenden Sie die Methode batchUpdate(). Damit werden Änderungen in einem Batch zusammengefasst. Wenn also eine Anfrage fehlschlägt, werden keine der anderen (möglicherweise abhängigen) Änderungen geschrieben.

Die Methode batchUpdate() gibt einen Antworttext zurück, der eine Antwort für jede Anfrage enthält. Jede Antwort belegt denselben Index wie die entsprechende Anfrage. Bei Anfragen ohne anwendbare Antwort ist die Antwort an diesem Index leer.

Hinweis

Führen Sie die folgenden Aufgaben aus, bevor Sie mit den Aufgaben auf dieser Seite fortfahren:

  • Führen Sie die Autorisierung/Authentifizierung und die Einrichtung der Anmeldedaten gemäß der Anleitung für das Early Adopter-Programm durch.

Metadaten, Einstellungen oder Elemente aktualisieren

Im folgenden Beispiel wird gezeigt, wie die Metadaten eines Formulars aktualisiert werden. Die Struktur ist jedoch für Inhalte und Einstellungen dieselbe. Hier werden die Anfragen updateItem oder updateSettings anstelle von updateFormInfo verwendet. Für jede Anfrage geben Sie den Namen des zu ändernden Felds und den aktualisierten Wert sowie einen updateMask-Wert an, um die Änderungen auf die von Ihnen angegebenen Felder zu beschränken.

REST

Rufen Sie zum Aktualisieren der Beschreibung des Formulars die Methode batchUpdate() mit der Formular-ID und dem aktualisierten Beschreibungswert auf.

Beispiel für einen Anfragetext

    "requests": [{
        "updateFormInfo": {
            "info": {
                "description": "Please complete this quiz based on this week's readings for class."
            },
            "updateMask": "description"
        }
    }]

Python

forms/snippets/update_form.py
from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools

SCOPES = "https://www.googleapis.com/auth/forms.body"
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"

store = file.Storage("token.json")
creds = None
if not creds or creds.invalid:
  flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES)
  creds = tools.run_flow(flow, store)

form_service = discovery.build(
    "forms",
    "v1",
    http=creds.authorize(Http()),
    discoveryServiceUrl=DISCOVERY_DOC,
    static_discovery=False,
)

form = {
    "info": {
        "title": "Update metadata example for Forms API!",
    }
}

# Creates the initial Form
createResult = form_service.forms().create(body=form).execute()

# Request body to add description to a Form
update = {
    "requests": [
        {
            "updateFormInfo": {
                "info": {
                    "description": (
                        "Please complete this quiz based on this week's"
                        " readings for class."
                    )
                },
                "updateMask": "description",
            }
        }
    ]
}

# Update the form with a description
question_setting = (
    form_service.forms()
    .batchUpdate(formId=createResult["formId"], body=update)
    .execute()
)

# Print the result to see it now has a description
getresult = form_service.forms().get(formId=createResult["formId"]).execute()
print(getresult)

Node.js

forms/snippets/update_form.js
import path from 'node:path';
import {authenticate} from '@google-cloud/local-auth';
import {forms} from '@googleapis/forms';

/**
 * Creates a new form and then updates it to add a description.
 */
async function updateForm() {
  // Authenticate with Google and get an authorized client.
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Forms API client.
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  // The initial form to be created.
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };

  // Create the new form.
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });

  if (!createResponse.data.formId) throw new Error('Form ID not returned.');

  console.log(`New formId was: ${createResponse.data.formId}`);

  // Request body to add a description to the form.
  const update = {
    requests: [
      {
        updateFormInfo: {
          info: {
            description:
              "Please complete this quiz based on this week's readings for class.",
          },
          // The updateMask specifies which fields to update.
          updateMask: 'description',
        },
      },
    ],
  };

  // Send the batch update request to update the form.
  const result = await formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });

  console.log(result.data);
  return result.data;
}

Hinzufügen

Im folgenden Beispiel wird gezeigt, wie einem Formular neuer Inhalt hinzugefügt wird. Wenn Sie neue Inhalte hinzufügen, müssen Sie einen Ort mit einem Index angeben, an dem die neuen Inhalte eingefügt werden sollen. Wenn Sie beispielsweise den Index 0 für einen Ort angeben, wird der Inhalt am Anfang des Formulars eingefügt.

REST

Wenn Sie dem Formular ein Element hinzufügen möchten, rufen Sie die Methode batchUpdate() mit der Formular-ID, den Informationen des Elements und dem ausgewählten Speicherort auf.

Beispiel für einen Anfragetext

"requests": [{
    "createItem": {
        "item": {
            "title": "Homework video",
            "description": "Quizzes in Google Forms",
            "videoItem": {
                "video": {
                     "youtubeUri": "https://www.youtube.com/watch?v=Lt5HqPvM-eI"
                }
            }},
        "location": {
          "index": 0
        }
}]

Python

forms/snippets/add_item.py
from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools

SCOPES = "https://www.googleapis.com/auth/forms.body"
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"

store = file.Storage("token.json")
creds = None
if not creds or creds.invalid:
  flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES)
  creds = tools.run_flow(flow, store)

form_service = discovery.build(
    "forms",
    "v1",
    http=creds.authorize(Http()),
    discoveryServiceUrl=DISCOVERY_DOC,
    static_discovery=False,
)

form = {
    "info": {
        "title": "Update item example for Forms API",
    }
}

# Creates the initial Form
createResult = form_service.forms().create(body=form).execute()

# Request body to add a video item to a Form
update = {
    "requests": [
        {
            "createItem": {
                "item": {
                    "title": "Homework video",
                    "description": "Quizzes in Google Forms",
                    "videoItem": {
                        "video": {
                            "youtubeUri": (
                                "https://www.youtube.com/watch?v=Lt5HqPvM-eI"
                            )
                        }
                    },
                },
                "location": {"index": 0},
            }
        }
    ]
}

# Add the video to the form
question_setting = (
    form_service.forms()
    .batchUpdate(formId=createResult["formId"], body=update)
    .execute()
)

# Print the result to see it now has a video
result = form_service.forms().get(formId=createResult["formId"]).execute()
print(result)

Node.js

forms/snippets/add_item.js
import path from 'node:path';
import {authenticate} from '@google-cloud/local-auth';
import {forms} from '@googleapis/forms';

/**
 * Creates a new form and adds a video item to it.
 */
async function addItem() {
  // Authenticate with Google and get an authorized client.
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Forms API client.
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  // The initial form to be created.
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };

  // Create the new form.
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });

  if (!createResponse.data.formId) {
    throw new Error('Form ID not returned.');
  }

  console.log(`New formId was: ${createResponse.data.formId}`);

  // Request body to add a video item to the form.
  const update = {
    requests: [
      {
        createItem: {
          item: {
            title: 'Homework video',
            description: 'Quizzes in Google Forms',
            videoItem: {
              video: {
                youtubeUri: 'https://www.youtube.com/watch?v=Lt5HqPvM-eI',
              },
            },
          },
          // The location to insert the new item.
          location: {
            index: 0,
          },
        },
      },
    ],
  };

  // Send the batch update request to add the item to the form.
  const updateResponse = await formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });

  console.log(updateResponse.data);
  return updateResponse.data;
}

Bestellung anfordern

Die Methode batchUpdate() akzeptiert ein Array von untergeordneten Anfragen wie createItem und updateItem. Untergeordnete Anfragen werden einzeln in der Reihenfolge validiert, in der sie bereitgestellt werden.

Beispiel: Eine batchUpdate-Anfrage enthält ein requests-Array mit zwei createItem-Unteranfragen. Unteranfrage A hat location.index 0 und Unteranfrage B hat location.index 1. Wenn das requests-Array [A, B] ist, ist batchUpdate erfolgreich. Wenn das Array [B, A] ist, schlägt batchUpdate fehl, da location.index 1 nur gültig ist, wenn das Formular bereits ein Element am Index 0 enthält.