更新表单或测验

如需向表单添加内容或更新设置、元数据或内容,请使用 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
'use strict';

const path = require('path');
const google = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

async function runSample(query) {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const forms = google.forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await forms.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 forms.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(res.data);
  return res.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

添加项目

以下示例展示了如何向表单添加新内容。添加新内容时,您必须提供应插入新内容的位置及索引。例如,索引为 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
'use strict';

const path = require('path');
const google = require('@googleapis/forms');
const {authenticate} = require('@google-cloud/local-auth');

async function runSample(query) {
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const forms = google.forms({
    version: 'v1',
    auth: authClient,
  });
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };
  const createResponse = await forms.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 forms.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });
  console.log(updateResponse.data);
  return updateResponse.data;
}

if (module === require.main) {
  runSample().catch(console.error);
}
module.exports = runSample;

申请订单

batchUpdate() 方法接受子请求数组,例如 createItemupdateItem。按照提供子请求的顺序,一次验证一个子请求。

示例:batchUpdate 请求具有包含两个 createItem 子请求的 requests 数组。子请求 A 的 location.index 为 0,子请求 B 的 location.index 为 1。如果 requests 数组为 [A, B],则 batchUpdate 将会成功。如果数组为 [B, A],则 batchUpdate 将失败,因为除非表单已包含索引 0 处的项目,否则 location.index 1 无效。