تعديل نموذج أو اختبار

لإضافة محتوى إلى نموذج أو تعديل الإعدادات أو البيانات الوصفية أو المحتوى، استخدِم طريقة 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 '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 إلى إدراج المحتوى في بداية النموذج.

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 '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. يحتوي الطلب الفرعي "أ" على location.index 0 ويحتوي الطلب الفرعي "ب" على location.index 1. إذا كانت مصفوفة requests هي [A, B]، سينجح طلب batchUpdate. إذا كانت المصفوفة هي [B, A]، سيتعذّر تنفيذ طلب batchUpdate، لأنّ location.index 1 غير صالح ما لم يكن النموذج يحتوي على عنصر بالفهرس 0.