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

Để thêm nội dung vào 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 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 trong một 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 những yêu cầu không có phản hồi nào áp dụng, phản hồi tại chỉ mục đó sẽ trống.

Trước khi bắt đầu

Hãy thực hiện các việc sau trước khi tiếp tục thực hiện các việc trên trang này:

  • Hoàn tất quy trình uỷ quyền/xác thực và thiết lập thông tin đăng nhập theo hướng dẫn trong Chương trình 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 biểu mẫu, nhưng cấu trúc này cũng tương tự đối với nội dung và chế độ cài đặt. Chúng sử dụng các 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 các thay đổi đối với những 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() bằng mã nhận dạng 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
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;
}

Thêm một mục

Ví dụ sau đây cho thấy cách thêm nội dung mới vào 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 vào đầ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
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;
}

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ụ, chẳng hạn như createItemupdateItem. Các yêu cầu phụ được xác thực lần lượt theo thứ tự mà chúng được cung cấp.

Ví dụ: Yêu cầu batchUpdate có một mảng requests với 2 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], thì 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.