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

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

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

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

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

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

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

בדוגמה הבאה מוצג איך לעדכן את המטא-נתונים של טופס, אבל המבנה זהה לתוכן ולהגדרות – נעשה שימוש בבקשות 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
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

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

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