עדכון של טופס או בוחן

כדי להוסיף תוכן לטופס או לעדכן את ההגדרות, המטא-נתונים או התוכן, משתמשים ב-method‏ batchUpdate(), שמקבץ את השינויים יחד באצווה. כך, אם בקשה אחת נכשלת, אף אחד מהשינויים האחרים (שעשויים להיות תלויים) לא נכתב.

השיטה batchUpdate() מחזירה גוף תשובה, שכולל תשובה לכל בקשה. כל תשובה נמצאת באותו אינדקס של הבקשה המתאימה. לבקשות ללא תשובה רלוונטית, התגובה באותו אינדקס תהיה ריקה.

לפני שמתחילים

לפני שממשיכים במשימות שבדף הזה, צריך לבצע את הפעולות הבאות:

  • להשלים את ההרשאה/האימות והגדרת פרטי הכניסה לפי ההוראות של תוכנית Early Adopter

עדכון של מטא-נתונים, הגדרות או פריטים

הדוגמה הבאה מראה איך לעדכן את המטא-נתונים של טופס, אבל המבנה זהה לתוכן ולהגדרות – הם משתמשים בבקשות updateItem או updateSettings במקום ב-updateFormInfo. לכל בקשה, צריך לציין את שם השדה שרוצים לשנות ואת הערך המעודכן, יחד עם ערך updateMask כדי להגביל את השינויים בשדות שציינתם.

REST

כדי לעדכן את תיאור הטופס, צריך להפעיל את השיטה 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

כדי להוסיף פריט לטופס, צריך להפעיל את השיטה 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() מקבלת מערך של בקשות משנה, כמו createItem ו-updateItem. המערכת מאמתת את הבקשות המשניות אחת אחרי השנייה, לפי הסדר שבו הן ניתנות.

דוגמה: בקשת batchUpdate כוללת מערך requests עם שתי בקשות משנה מסוג createItem. בבקשת המשנה א' הערך של location.index הוא 0, ובבקשת המשנה ב' הערך של location.index הוא 1. אם מערך requests הוא [A, B], הפונקציה batchUpdate תצליח. אם המערך הוא [B, A], הפונקציה batchUpdate תיכשל כי הערך location.index‏ 1 לא תקף אלא אם הטופס כבר מכיל פריט במדד 0.