更新表單或測驗

如要將內容新增至表單,或更新設定、中繼資料或內容,請使用 batchUpdate() 方法,將變更內容分批歸類,這樣一來,如果其中一項要求失敗,系統就不會寫入其他 (可能相依的) 變更。

batchUpdate() 方法會傳回回應內文,其中包含每個要求的回應。每個回應佔用的索引都與對應要求相同;如果要求沒有適用的回應,該索引的回應就會是空白。

事前準備

請先完成下列工作,再繼續執行本頁面的工作:

  • 按照搶先體驗計畫的說明,完成授權/驗證和憑證設定

更新中繼資料、設定或項目

以下範例說明如何更新表單的中繼資料,但內容和設定的結構相同,都是使用 updateItemupdateSettings 要求,而非 updateFormInfo。對於每項要求,您都要提供要變更的欄位名稱和更新值,以及 updateMask 值,將變更限制在您指定的欄位。

REST

如要更新表單說明,請使用表單 ID 和更新後的說明值呼叫 batchUpdate() 方法。

要求主體範例

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

新增項目

以下範例說明如何在表單中新增內容。新增內容時,您必須提供索引位置,以便插入新內容。舉例來說,索引為 0 的位置會在表單開頭插入內容。

REST

如要在表單中新增項目,請使用表單 ID、項目資訊和所需位置呼叫 batchUpdate() 方法。

要求主體範例

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

要求訂單

batchUpdate() 方法會接受子要求陣列,例如 createItemupdateItem。系統會依序驗證子要求。

範例:batchUpdate 要求具有兩個 createItem 子要求的 requests 陣列。requests子要求 A 的 location.index 為 0,子要求 B 的 location.index 為 1。如果 requests 陣列為 [A, B],batchUpdate 就會成功。如果陣列為 [B, A],則 batchUpdate 會失敗,因為除非表單已在索引 0 處包含項目,否則 location.index1 無效。