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

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