Cập nhật biểu mẫu hoặc bài kiểm tra

Để thêm nội dung vào một biểu mẫu hoặc cập nhật chế độ cài đặt, siêu dữ liệu hoặc nội dung, hãy sử dụng phương thức batchUpdate(). Phương thức này sẽ nhóm các thay đổi lại với nhau theo lô để nếu một yêu cầu không thành công, thì không có thay đổi nào khác (có thể phụ thuộc) được ghi.

Phương thức batchUpdate() trả về một nội dung phản hồi, trong đó có một phản hồi cho mỗi yêu cầu. Mỗi phản hồi chiếm cùng một chỉ mục với yêu cầu tương ứng; đối với các yêu cầu không có phản hồi phù hợp, phản hồi tại chỉ mục đó sẽ trống.

Trước khi bắt đầu

Thực hiện các nhiệm vụ sau trước khi tiếp tục với các nhiệm vụ trên trang này:

  • Hoàn tất việc uỷ quyền/xác thực và thiết lập thông tin xác thực theo hướng dẫn của Chương trình dành cho người dùng sớm

Cập nhật siêu dữ liệu, chế độ cài đặt hoặc mục

Ví dụ sau đây cho biết cách cập nhật siêu dữ liệu của một biểu mẫu, nhưng cấu trúc giống nhau đối với nội dung và chế độ cài đặt – các yêu cầu này sử dụng yêu cầu updateItem hoặc updateSettings thay vì updateFormInfo. Đối với mỗi yêu cầu, bạn cung cấp tên của trường cần thay đổi và giá trị đã cập nhật, cùng với giá trị updateMask để giới hạn thay đổi đối với các trường mà bạn đã chỉ định.

REST

Để cập nhật nội dung mô tả của biểu mẫu, hãy gọi phương thức batchUpdate() với mã biểu mẫu và giá trị nội dung mô tả đã cập nhật.

Nội dung yêu cầu mẫu

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

Thêm một mục

Ví dụ sau đây cho thấy cách thêm nội dung mới vào một biểu mẫu. Khi thêm nội dung mới, bạn phải cung cấp một vị trí có chỉ mục nơi nội dung mới sẽ được chèn. Ví dụ: một vị trí có chỉ mục 0 sẽ chèn nội dung ở đầu biểu mẫu.

REST

Để thêm một mục vào biểu mẫu, hãy gọi phương thức batchUpdate() bằng mã biểu mẫu, thông tin của mục và vị trí mong muốn.

Nội dung yêu cầu mẫu

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

Yêu cầu đặt hàng

Phương thức batchUpdate() chấp nhận một mảng các yêu cầu phụ như createItemupdateItem. Các yêu cầu phụ được xác thực lần lượt theo thứ tự được cung cấp.

Ví dụ: Yêu cầu batchUpdate có một mảng requests với hai yêu cầu phụ createItem. Yêu cầu phụ A có location.index 0 và yêu cầu phụ B có location.index 1. Nếu mảng requests là [A, B], thì batchUpdate sẽ thành công. Nếu mảng là [B, A], batchUpdate sẽ không thành công vì location.index 1 không hợp lệ, trừ phi biểu mẫu đã chứa một mục ở chỉ mục 0.