یک فرم یا مسابقه را به روز کنید

برای افزودن محتوا به یک فرم یا به‌روزرسانی تنظیمات، فراداده یا محتوا، از متد batchUpdate() استفاده کنید که تغییرات را در یک دسته گروه‌بندی می‌کند، به طوری که اگر یک درخواست با شکست مواجه شود، هیچ یک از تغییرات دیگر (که به طور بالقوه وابسته هستند) نوشته نمی‌شوند.

متد batchUpdate() یک بدنه پاسخ را برمی‌گرداند که در آن برای هر درخواست، یک پاسخ وجود دارد. هر پاسخ، اندیس مشابه درخواست مربوطه را اشغال می‌کند؛ برای درخواست‌هایی که پاسخ قابل استفاده‌ای ندارند، پاسخ در آن اندیس خالی خواهد بود.

قبل از اینکه شروع کنی

قبل از ادامه‌ی وظایف این صفحه، وظایف زیر را انجام دهید:

  • مراحل مجوز/احراز هویت و تنظیم اعتبارنامه‌ها را در دستورالعمل‌های برنامه‌ی پذیرندگان اولیه تکمیل کنید.

به‌روزرسانی فراداده، تنظیمات یا موارد

مثال زیر نحوه به‌روزرسانی متادیتای یک فرم را نشان می‌دهد، اما ساختار برای محتوا و تنظیمات یکسان است - آنها از درخواست‌های updateItem یا updateSettings به جای updateFormInfo استفاده می‌کنند. برای هر درخواست، نام فیلدی که باید تغییر کند و مقدار به‌روزرسانی شده، همراه با یک مقدار updateMask برای محدود کردن تغییرات در فیلدهایی که مشخص کرده‌اید، ارائه می‌دهید.

استراحت

برای به‌روزرسانی توضیحات فرم، متد batchUpdate() را با شناسه فرم و مقدار توضیحات به‌روزرسانی‌شده فراخوانی کنید.

متن درخواست نمونه

    "requests": [{
        "updateFormInfo": {
            "info": {
                "description": "Please complete this quiz based on this week's readings for class."
            },
            "updateMask": "description"
        }
    }]

پایتون

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)

نود جی اس

فرم‌ها/قطعه کدها/update_form.js
import path from 'node:path';
import {authenticate} from '@google-cloud/local-auth';
import {forms} from '@googleapis/forms';

/**
 * Creates a new form and then updates it to add a description.
 */
async function updateForm() {
  // Authenticate with Google and get an authorized client.
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Forms API client.
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  // The initial form to be created.
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };

  // Create the new form.
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });

  if (!createResponse.data.formId) throw new Error('Form ID not returned.');

  console.log(`New formId was: ${createResponse.data.formId}`);

  // Request body to add a description to the form.
  const update = {
    requests: [
      {
        updateFormInfo: {
          info: {
            description:
              "Please complete this quiz based on this week's readings for class.",
          },
          // The updateMask specifies which fields to update.
          updateMask: 'description',
        },
      },
    ],
  };

  // Send the batch update request to update the form.
  const result = await formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: update,
  });

  console.log(result.data);
  return result.data;
}

یک مورد اضافه کنید

مثال زیر نحوه افزودن محتوای جدید به یک فرم را نشان می‌دهد. هنگام افزودن محتوای جدید، باید مکانی را با اندیس مشخص کنید که محتوای جدید باید در آن درج شود. به عنوان مثال، مکانی با اندیس 0 محتوا را در ابتدای فرم درج می‌کند.

استراحت

برای افزودن یک آیتم به فرم، متد 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
        }
}]

پایتون

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)

نود جی اس

فرم‌ها/قطعه کدها/add_item.js
import path from 'node:path';
import {authenticate} from '@google-cloud/local-auth';
import {forms} from '@googleapis/forms';

/**
 * Creates a new form and adds a video item to it.
 */
async function addItem() {
  // Authenticate with Google and get an authorized client.
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Forms API client.
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  // The initial form to be created.
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };

  // Create the new form.
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });

  if (!createResponse.data.formId) {
    throw new Error('Form ID not returned.');
  }

  console.log(`New formId was: ${createResponse.data.formId}`);

  // Request body to add a video item to the 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',
              },
            },
          },
          // The location to insert the new item.
          location: {
            index: 0,
          },
        },
      },
    ],
  };

  // Send the batch update request to add the item to the form.
  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 است. زیر درخواست A دارای location.index 0 و زیر درخواست B دارای location.index 1 است. اگر آرایه requests برابر با [A, B] باشد، batchUpdate با موفقیت انجام می‌شود. اگر آرایه برابر با [B, A] باشد، batchUpdate با شکست مواجه می‌شود، زیرا location.index 1 معتبر نیست مگر اینکه فرم از قبل حاوی یک آیتم در اندیس 0 باشد.