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 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 hat 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:

  • Schließen Sie die Autorisierung/Authentifizierung und die Einrichtung der Anmeldedaten gemäß der Anleitung für das Early Adopter-Programm ab.

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. Anstelle von updateFormInfo werden die Anfragen updateItem oder updateSettings 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 'path';
import {forms} from '@googleapis/forms';
import {authenticate} from '@google-cloud/local-auth';

async function updateForm() {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });
  console.log('New formId was: ' + createResponse.data.formId);

  // Request body to add description to a Form
  const update = {
    requests: [
      {
        updateFormInfo: {
          info: {
            description:
              'Please complete this quiz based on this week\'s readings for class.',
          },
          updateMask: 'description',
        },
      },
    ],
  };
  const res = await formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(res.data);
  return res.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 Speicherort 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

Rufen Sie die Methode batchUpdate() mit der Formular-ID, den Informationen des Elements und dem gewünschten Speicherort auf, um dem Formular ein Element hinzuzufügen.

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 'path';
import {forms} from '@googleapis/forms';
import {authenticate} from '@google-cloud/local-auth';

async function addItem() {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });
  console.log('New formId was: ' + createResponse.data.formId);

  // Request body to add video item to a 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',
              },
            },
          },
          location: {
            index: 0,
          },
        },
      },
    ],
  };
  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, wird batchUpdate erfolgreich ausgeführt. Wenn das Array [B, A] ist, schlägt batchUpdate fehl, da location.index 1 nur gültig ist, wenn das Formular bereits ein Element mit dem Index 0 enthält.