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

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