Memperbarui formulir atau kuis

Untuk menambahkan konten ke formulir atau memperbarui setelan, metadata, atau konten, gunakan metode batchUpdate(), yang mengelompokkan perubahan bersama-sama dalam batch sehingga jika satu permintaan gagal, tidak ada perubahan lain (yang mungkin bergantung) yang ditulis.

Metode batchUpdate() menampilkan isi respons, yang di dalamnya terdapat respons untuk setiap permintaan. Setiap respons menempati indeks yang sama dengan permintaan yang sesuai; untuk permintaan tanpa respons yang berlaku, respons pada indeks tersebut akan kosong.

Sebelum memulai

Lakukan tugas berikut sebelum melanjutkan tugas di halaman ini:

  • Selesaikan penyiapan otorisasi/autentikasi dan kredensial dalam petunjuk Program Pengadopsi Awal

Memperbarui metadata, setelan, atau item

Contoh berikut menunjukkan cara memperbarui metadata formulir, tetapi struktur nya sama untuk konten dan setelan—keduanya menggunakan permintaan updateItem atau updateSettings, bukan updateFormInfo. Untuk setiap permintaan, Anda memberikan nama kolom yang akan diubah dan nilai yang diperbarui, beserta nilai updateMask untuk membatasi perubahan pada kolom yang telah Anda tentukan.

REST

Untuk memperbarui deskripsi formulir, panggil metode batchUpdate() dengan ID formulir dan nilai deskripsi yang diperbarui.

Contoh isi permintaan

    "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;
}

Tambahkan item

Contoh berikut menunjukkan cara menambahkan konten baru ke formulir. Saat menambahkan konten baru, Anda harus memberikan lokasi dengan indeks tempat konten baru harus disisipkan. Misalnya, lokasi dengan indeks 0 akan menyisipkan konten di awal formulir.

REST

Untuk menambahkan item ke formulir, panggil metode batchUpdate() dengan ID formulir dan informasi item serta lokasi yang diinginkan.

Contoh isi permintaan

"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;
}

Urutan permintaan

Metode batchUpdate() menerima array sub-permintaan seperti createItem dan updateItem. Sub-permintaan divalidasi satu per satu dalam urutan yang diberikan.

Contoh: Permintaan batchUpdate memiliki array requests dengan dua sub-permintaan createItem. Sub-permintaan A memiliki location.index 0 dan sub-permintaan B memiliki location.index 1. Jika array requests adalah [A, B], batchUpdate akan berhasil. Jika arraynya adalah [B, A], batchUpdate akan gagal, karena location.index 1 tidak valid kecuali jika formulir sudah berisi item pada indeks 0.