Formu veya testi güncelleme

Forma içerik eklemek veya ayarları, meta verileri ya da içeriği güncellemek için batchUpdate() yöntemini kullanın. Bu yöntem, değişiklikleri toplu olarak gruplandırır. Böylece bir istek başarısız olursa diğer (potansiyel olarak bağımlı) değişikliklerin hiçbiri yazılmaz.

batchUpdate() yöntemi, her istek için bir yanıtın bulunduğu bir yanıt gövdesi döndürür. Her yanıt, karşılık gelen istekle aynı dizini kullanır. Geçerli yanıtı olmayan isteklerde, o dizindeki yanıt boş olur.

Başlamadan önce

Bu sayfadaki görevlere devam etmeden önce aşağıdaki görevleri gerçekleştirin:

  • Erken Erişim Programı talimatlarındaki yetkilendirme/kimlik doğrulama ve kimlik bilgileri kurulumunu tamamlayın.

Meta verileri, ayarları veya öğeleri güncelleme

Aşağıdaki örnekte, bir formun meta verilerinin nasıl güncelleneceği gösterilmektedir. Ancak içerik ve ayarların yapısı aynıdır. Bunlar, updateFormInfo yerine updateItem veya updateSettings isteklerini kullanır. Her istek için, değiştirilecek alanın adını ve güncellenen değeri, değişiklikleri belirttiğiniz alanlarla sınırlamak üzere bir updateMask değeriyle birlikte sağlarsınız.

REST

Formun açıklamasını güncellemek için form kimliği ve güncellenmiş açıklama değeriyle batchUpdate() yöntemini çağırın.

Örnek istek gövdesi

    "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;
}

Öğe ekleyin

Aşağıdaki örnekte, forma nasıl yeni içerik ekleneceği gösterilmektedir. Yeni içerik eklerken, yeni içeriğin ekleneceği dizine sahip bir konum sağlamanız gerekir. Örneğin, 0 dizinine sahip bir konum, içeriği formun başına ekler.

REST

Forma öğe eklemek için form kimliği, öğenin bilgileri ve istenen konumuyla birlikte batchUpdate() yöntemini çağırın.

Örnek istek gövdesi

"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;
}

Sipariş isteği

batchUpdate() yöntemi, createItem ve updateItem gibi bir dizi alt isteği kabul eder. Alt istekler, sağlandıkları sırayla tek tek doğrulanır.

Örnek: Bir batchUpdate isteğinde iki createItem alt isteği olan bir requests dizisi var. A alt isteğinde location.index 0, B alt isteğinde ise location.index 1 var. requests dizisi [A, B] ise batchUpdate başarılı olur. Dizi [B, A] ise form zaten 0 dizininde bir öğe içermediği sürece batchUpdate başarısız olur.location.index