第3章 $fh.forms

3.1. $fh.forms.getForms

$fh.forms.getForms(options, callback);

フォームサマリー情報のある JSON オブジェクトのアレイを返します。

注記

これらのフォームサマリー JSON オブジェクトには、完全フォーム定義が含まれていません。完全フォーム定義を取得するには、$fh.forms.getForm 関数を使用してください。

3.1.1. 例

//Get a list of forms associated with the project.
var options = {

};

$fh.forms.getForms(options,

/*
* Function executed with forms.
*/
function (err, response) {
  if (err) return handleError(err);

  //An Array Of Forms Associated With The Project
  var formsArray = response.forms;

   /*
     exampleForm: {
      _id: <<Form Id>>,
      name: <<Form Name>>,
      description: <<Form Description>>
      lastUpdatedTimestamp: <<Timestamp of when the form was last updated>>
    }
  */
  var exampleForm = formsArray[0];

  return callback(undefined, formsArray);
});

3.2. $fh.forms.getForm

  $fh.forms.getForm(options, callback)

3.2.1. 詳細

フォーム ID に基づいて特定のフォームモデルを取得します。フォーム ID は、$fh.forms.getForms 関数を使用して取得できます。

3.2.2. 例

$fh.forms.getForm({
  "_id": formId
}, function (err, form) {
  if (err) return handleError(err);


  /*
    A JSON object describing a full form object.
  */
  return callback(undefined, form);
});

3.3. $fh.forms.getPopulatedFormList

  $fh.forms.getPopulatedFormList(options, callback)

3.3.1. 詳細

フォーム ID 一覧に基づいてフォームモデルを取得します。

3.3.2. 例

$fh.forms.getPopulatedFormList({
  "formids": [formId1, formId2 ... ]
}, function (err, arrayOfForms) {
  if (err) return handleError(err);


  /*
    A JSON object describing a full form object.
  */
  return callback(undefined, arrayOfForms);
});

3.4. $fh.forms.getSubmissions

  $fh.forms.getSubmissions(options, callback)

3.4.1. 詳細

フィルター条件に基づいて全提出を一覧表示します。

3.4.2. submissionsObject

{
  submissions: [<SubmissionJSON>, <SubmissionJSON>]
}

3.4.3. 例

$fh.forms.getSubmissions({
  "formId": [formId1, formId2 ... ],
  "subid": [subId1, subId2 ...]
}, function (err, submissionsObject) {
  if (err) return handleError(err);


  /*
    An Object Containing An Array of JSON objects describing a full Submission object.
  */
  return callback(undefined, submissionsObject);
});

3.5. $fh.forms.getSubmission

  $fh.forms.getSubmission(options, callback)

3.5.1. 詳細

単一のフォーム提出を取得します。

3.5.2. 例

$fh.forms.getSubmissions({
  "submissionId": subId1
}, function (err, submission) {
  if (err) return handleError(err);


  /*
    A JSON object describing a full Submission object.
  */
  return callback(undefined, submission);
});

3.6. $fh.forms.getSubmissionFile

  $fh.forms.getSubmissionFile(options, callback)

3.6.1. 詳細

提出に含まれる単一ファイルをストリームします。ファイルには、提出ファイルフィールド内の fileGroupId フィールドを使用してアクセスします。

3.6.2. fileStreamObject

{
  stream: <Readable File Stream>
}

3.6.3. 例

$fh.forms.getSubmissionFile({
  "_id": fileGroupId
}, function (err, fileStreamObject) {
  if (err) return handleError(err);


  /**
  * Pipe the file stream to a writable stream (for example, a FileWriter)
  */
  fileStreamObject.stream.pipe(writable_stream);
  fileStreamObject.stream.resume();
});

3.7. フォーム JSON の定義

フォーム JSON オブジェクトには、フォーム処理に必要なすべての情報が含まれています。

{
   "_id":"<<24 Character Form ID>>",
   "description":"This is an example form definition",
   "name":"Example Form",
   "updatedBy":"<<User ID of the person that last updated the form>>",
   "lastUpdatedTimestamp":1410876316105, //Time the form was last updated.
   "subscribers":[
   //Email addresses to be notified when a submission has been made against this form.
    "notifiedUser1@example.com",
    "notifiedUser2@example.com"
   ],
   "pageRules":[
      <<Page Rule JSON Object>>
   ],
   "fieldRules":[
      <<Field Rule JSON Object>>
   ],
   "pages":[
      <<Page JSON Object>>,
   ],
   //Convenient reference for the index of a page with <<Page Id>> in the "pages" array.
   "pageRef":{
      "<<Page Id>>":0,
      "<<Page Id>>":1
   },
   //Convenient reference for the index of a field. Both the page index and field index are given.
   "fieldRef":{
      "<<Field Id>>":{
         "page":0,
         "field":0
      },
      "<<Field Id>>":{
         "page":0,
         "field":1
      }
   }
}

3.7.1. ページ

{
   "_id":"<<Page ID>>",
   "name":"Page 1",
   "fields":[
      <<Field JSON Object>>
   ]
}

3.7.2. フィールド

{
  "_id":"<<Field ID>>",
   "required":true,
   "type":"text",//Field Type
   "name":"A Sample Text Field",
   "repeating":false/true //Boolean that describes if a field is repeating or not.
   "fieldOptions":{
      "validation":{ // Optional validation parameters for the form.
         "validateImmediately":true //Flag for whether field inputs should be immediately validated (for example, On-Blur on a Client App.)
      },
      "definition": {// Optional definition options.
          "minRepeat": 2, //Minimum number of entries for this field.
          "maxRepeat": 5 //Maximum number of entries for this field.
      }
   }
}

3.7.3. ページルール

この JSON オブジェクトは、Studio 内で作成されるページルールを記述します。

{
   "type":"skip",//A "skip" or "show" page rule
   "_id":"<<ID of the Page Rule>>",
   "targetPage":[
      "<<ID of the Page targeted by the Page Rule>>"
   ],
   "ruleConditionalStatements":[
      {
         "sourceField":"<<ID of the Field this condition is sourcing data from>>",
         "restriction":"is",// Comparator operator for the conditional statement.
         "sourceValue":"skippage" //Value To Compare.
      }
   ],
   //Combinator for "ruleConditionalStatements".  Can be "and" or "or".
   "ruleConditionalOperator":"and",
}

3.7.4. フィールドルール

この JSON オブジェクトは、Studio 内で作成されるフィールドルールを記述します。

{
   "type":"hide/show", //A "hide" or "show" field rule
   "_id":"<<ID of the Field Rule>>",
   "targetField":[
      "<<ID of the Field targeted by the Field Rule>>"
   ],
   "ruleConditionalStatements":[
      {
         "sourceField":"<<ID of the Field this condition is sourcing data from>",
         "restriction":"is",// Comparator operator for the conditional statement.
         "sourceValue":"hideMe" //Value To Compare.
      }
   ],
   //Combinator for "ruleConditionalStatements".  Can be "and" or "or".
   "ruleConditionalOperator":"and"
}

3.8. $fh.forms.getTheme

  $fh.forms.getTheme(options, callback)

3.8.1. 詳細

プロジェクトに割り当てられているテーマを表す JSON オブジェクトを読み込みます。

3.8.2. 例

//Currently no parameters for loading a theme.
var options = {

};

$fh.forms.getTheme({}, function (err, theme) {
  if (err) return handleError(err);

  return callback(undefined, theme);
});

3.8.3. $fh.forms.getAppClientConfig

  $fh.forms.getAppClientConfig(options, callback)

3.8.4. 詳細

プロジェクトに関連付けられているクライアント設定に含まれる JSON オブジェクトを返します。これらは Studio 内で設定されます。

3.8.5. 例

//Currently no options for loading app config.
var options = {

};

$fh.forms.getAppClientConfig(options, function (err, clientConfig) {
  if (err) return handleError(err);


  return callback(undefined, clientConfig);
});

3.8.6. クライアント設定の JSON オブジェクト

{
  "sent_items_to_keep_list": [5, 10, 20, 30, 40, 50, 100], //Array representing options available to
  "targetWidth": 480, //Camera Photo Width
  "targetHeight": 640, //Camera Photo Height
  "quality": 75, //Camera Photo Quality
  "debug_mode": false, //Set the Client To Debug Mode
  "logger" : false, //Client Logging
  "max_retries" : 0, //Maximum number of failed uplod attempts before returning an error to the user
  "timeout" : 30,// Number of seconds before a form upload times out.
  "log_line_limit": 300,//Maximum number of log entries before rotating logs
  "log_email": "test@example.com" //The email address that logs are sent to.
}

3.9. $fh.forms.submitFormData

   $fh.forms.submitFormData(options, callback)

3.9.1. 詳細

フォーム提出を表す JSON オブジェクトを提出します。

3.9.1.1. 例

var options = {
  "submission": <<Submission JSON Object>>,
  "appClientId": <<ID Of The Client Making The Submission.>>
};

$fh.forms.submitFormData(options, function(err,data){
  if(err) return callback(err);

  return callback(null,data);
});

3.9.2. 提出の JSON オブジェクト

{
  "formId": "<<ID Of Form Submitting Agains>>",
  "deviceId": "<<ID of the device submitting the form>>",
  "deviceIPAddress": "<<IP Address of the device submitting the form>>",
  "formFields": [<<Field Entry JSON Object>>],
  "deviceFormTimestamp": "<<lastUpdatedTimestamp of the Form that the submission was submitted against.>>",
  "comments": [{ //Optional comments related to the submission
    "madeBy": "user",
    "madeOn": "12/11/10",
    "value": "This is a comment"
  }]
}

3.9.3. フィールドエントリーの JSON オブジェクト

{
  fieldId: <<ID Of The Field "fieldValues" Are Submitted Against>>,
  fieldValues: [<<Field Value Entry>>]
}

3.9.4. フィールド値のエントリー

以下では、各タイプのフィールド提出に必須のデータ形式を示しています。

  • Text: 文字列
  • TextArea: 文字列
  • Number: 数値
  • Radio: 文字列 (フォームで定義されている Radio フィールドのいずれかのオプションであること)
  • Dropdown: 文字列 (フォームで表示されている Dropdown のいずれかのオプションであること)
  • Webstite: 文字列
  • Email: 文字列 (有効な E メールの形式であること)
  • DateStamp - 日付のみ: 文字列 (形式: DD/MM/YYYY)
  • DateStamp - 時間のみ: 文字列 (形式: HH:SS)
  • DateStamp - 日付 & 時間: 文字列 (形式: YYYY-MM-DD HH:SS)

チェックボックス

{
  selections: ["Check box Option 1", .... , "Check box Option 4"]
}

位置 (およびマップフィールド) - 緯度 & 経度

{
  lat: <<Valid Latitude Value>,
  long: <<Valid Longitude Value>>
}

位置 - 偏北距離 & 偏東距離

{
  zone: "11U",
  eastings: 594934,
  northings: 5636174
}

ファイルベースのフィールド - ファイル、写真、署名

{
  fileName: <<Name of the file to be uploaded>>,
  fileType: <<Valid mime type of the file>>,
  fileSize: <<Size of the file in Bytes>>,
  fileUpdateTime: <<Timestamp of the time the file was saved to device>>,
  hashName: "filePlaceHolder12345" //A unique identifer for the fole. NOTE: Must begin with "filePlaceHolder"
}
注記

hashName パラメーターはすべて filePlaceHolder で始まる必要があり、それ以外の場合は提出が拒否されます。

3.10. $fh.forms.getSubmissionStatus

  $fh.forms.getSubmissionStatus(options, callback)

3.10.1. 詳細

提出の現在のステータスを返します。

3.10.2. 例

var options = {
  submission: {
    //This is the submission ID returned when the $fh.forms.submitFormData function returns.
    submissionId: "<<Remote Submission ID>>"
  }
};

$fh.forms.getSubmissionStatus(options, function(err, submissionStatus){
   if(err) return handleError(err);

  return callback(undefined, submissionStatus);
});

3.10.3. 提出ステータスの JSON オブジェクト

注記

提出は、$fh.forms.completeSubmission 関数が呼び出された後でのみ、完了とマークされます。このため、pendingFiles アレイが空白となり、status が保留として設定される場合があります。

{
  "status": "pending/complete", //Status can either be pending or complete
  "pendingFiles": [
    "<<hashName of file not uploaded yet. (for example, filePlaceHolder1234)>>"
  ]
}

3.11. $fh.forms.submitFormFile

  $fh.forms.submitFormFile(options, callback)

3.11.1. 詳細

提出にファイルをアップロードします。

注記

ファイルは $fh.forms.submitFormData 関数を使用して提出 JSON オブジェクトに追加され、提出済みである必要があります。

注記

提出にアップロードするファイルは、ローカルファイルシステムに既に存在する必要があります。

警告

keepFile パラメーターが true に設定されていない場合は、アップロードが完了すると、提出にアップロードされるファイルはファイルシステムから削除されます。

3.11.2. 例

var options = {
  "submission": {
    "fileId": "<<The File hashName>>",
    "submissionId": "<<The Submission ID Containing The File Input>>",
    "fieldId": "<<Field Id The File Is Being Submitted Against>>",
    "fileStream": "<</path/to/the/file/stored/locally>>" //path to the file
    "keepFile": true/false //Keep the file storated at "fileStream" when it has been uploaded.
  }
 }

$fh.forms.submitFormFile(options, function(err, submitFileResult){
  if(err) return handleError(err);

  //File upload has completed successfully
  return callback(undefined, submitFileResult);
});

3.11.3. submitFileResult JSON オブジェクト

{
  status: 200 //Indicating that the file has uploaded successfully
  savedFileGroupId: <<Server ID of the file held in the submission>>
}

3.12. $fh.forms.completeSubmission

  $fh.forms.completeSubmission(options, callback)

3.12.1. 詳細

提出を完了としてマークします。提出 JSON の一部として提出された全ファイルがアップロードされていることをチェックします。

提出が正常に完了していれば、completeResult JSON オブジェクトに以下が含まれます。

{
  "status": "complete"
}

提出されたファイルがアップロードされていなければ、completeResult JSON オブジェクトに以下が含まれます。

{
  "status": "pending",
  "pendingFiles": [
    "<<hashName of file not uploaded yet. (for example, filePlaceHolder1234)>>"
  ]
}

3.12.2. 例

var options = {
  "submission": {
      "submissionId": "<<The ID of the Submission to Complete>>"
    }
}

$fh.forms.completeSubmission(options, function (err, completeResult) {
  if (err) return handleError(err);

  return callback(undefined, completeResult);
});

3.13. $fh.forms.createSubmissionModel

3.13.1. 詳細

$fh.forms.createSubmissionModel 関数は、フォームを作成および提出する別のメソッドになります。

提出モデルは、提出作成プロセスを容易にする便利な関数を提供します。

3.13.2. 例

var options = {
  "form": <<A Form JSON Object Obtained using $fh.forms.getForm>>
};

$fh.forms.createSubmissionModel(options, function(err, submissionModel){
  if (err) return handleError(err);

  //Now use the Submisison Model Functions To Add data to the Submission
  var fieldInputOptions = {
    "fieldId": "<<The ID of the field To Add Data To>>",
    "fieldCode": "<<The fieldCode of the field To Add Data To>>"
    "index": "<<The index to add the value to>>" //(This is used for repeating fields with mutiple values)
    "value": "<<A valid input value to add to the submission>>"
  };

  //Note: the addFieldInput function is not asynchronous
  var error = submissionModel.addFieldInput(fieldInputOptions);

  if(error){
    return handleError(error);
  }

  /*
  Submitting the data as part of a submission.
  This function will upload all files passed to the submission using the addFieldInput function
  */
  submissionModel.submit(function(err, submissionId){
    if(err) return handleError(err);

    return callback(undefined, submissionId);
  });
});

3.14. $fh.forms.registerListener

注記

お使いの package.jsonfh-mbaas-api のバージョンは、4.8.0 以降である必要があります。

3.14.1. 詳細

$fh.forms.registerListener 関数を使用すると、EventEmitter オブジェクトを登録して、発生する提出イベントをリッスンすることができます。

注記

$fh.forms.registerListener$fh.forms.deregisterListener 関数は EventEmitter オブジェクトをパラメーターとしてのみ受け付けます。

//NodeJS Events Module. Note, this is required to register event emitter objects to forms.
var events = require('events');
var submissionEventListener = new events.EventEmitter();

$fh.forms.registerListener(submissionEventListener, function(err){
  if (err) return handleError(err);

  //submissionEventListener has now been registered with the $fh.forms Cloud API. Any valid Forms Events will now emit.
});

3.14.2. イベント: submissionStarted

このイベントは、提出が提出され、検証、データベースに保存されると毎回生成されます。これは、提出の一部としてファイルがアップロードされる に行われます。

submissionStarted イベントに渡されるオブジェクトには、以下のパラメーターが含まれています。

{
    "submissionId": "<<24-character submission ID>>",
    "submissionStartedTimestamp": "<<2015-02-04T19:18:58.746Z>>"
}
//NodeJS Events Module. Note, this is required to register event emitter objects to forms.
var events = require('events');
var submissionEventListener = new events.EventEmitter();

submissionEventListener.on('submissionStarted', function(params){
  var submissionId = params.submissionId;
  var submissionStartedTimestamp = params.submissionStartedTimestamp;
  console.log("Submission with ID " + submissionId + " has started at " + submissionStartedTimestamp);
});

$fh.forms.registerListener(submissionEventListener, function(err){
  if (err) return handleError(err);

  //submissionEventListener has now been registered with the $fh.forms Cloud API. Any valid Forms Events will now emit.
});

3.14.3. イベント: submissionComplete

このイベントは、提出が提出、検証、データベースに保存され、全ファイルがデータベースに保存されて提出が検証されると毎回生成されます。これで提出は、$fh.forms.getSubmission クラウド API を使って処理する準備が整ったことになります。

//NodeJS Events Module. Note, this is required to register event emitter objects to forms.
var events = require('events');
var submissionEventListener = new events.EventEmitter();

submissionEventListener.on('submissionComplete', function(params){
  var submissionId = params.submissionId;
  var submissionCompletedTimestamp = params.submissionCompletedTimestamp;
  console.log("Submission with ID " + submissionId + " has completed at " + submissionCompletedTimestamp);
});

$fh.forms.registerListener(submissionEventListener, function(err){
  if (err) return handleError(err);

  //submissionEventListener has now been registered with the $fh.forms Cloud API. Any valid Forms Events will now emit.
});

イベントに渡される params オブジェクトには、以下が含まれています。

{
    "submissionId": "<<24-character submission ID>>",
    "submissionCompletedTimestamp": "<<2015-02-04T19:18:58.746Z>>",
    "submission": "<<JSON definition of the Completed Submission.>>"
}

3.14.4. イベント: submissionError

このイベントは、提出の作成中にエラーが発生すると生成されます。

//NodeJS Events Module. Note, this is required to register event emitter objects to forms.
var events = require('events');
var submissionEventListener = new events.EventEmitter();

submissionEventListener.on('submissionError', function(error){
  console.log("Error Submitting Form");
  console.log("Error Type: ", error.type);
});

$fh.forms.registerListener(submissionEventListener, function(err){
 if (err) return handleError(err);

 //submissionEventListener has now been registered with the $fh.forms Cloud API. Any valid Forms Events will now emit.
});

3.14.4.1. 提出エラーのタイプ

提出エラーは、エラーの理由によって以下の異なるタイプに分けられます。

3.14.4.1.1. 検証エラー

提出されたデータが有効なものではありません。応答は以下の形式になります。

注記

繰り返しフィールドの場合、エラーメッセージはフィールドに入力された値と同じ順序になります。

{
  type: 'validationError',
  error: {
       valid: < true / false >,
       < fieldId1 >: {
           valid: < true / false >,
           errorMessages: [
               "Validation Error Message 1",
               "Validation Error Message 2"
           ]
       },
       ....,
       < fieldIdN >: {
           valid: < true / false >,
           errorMessages: [
               "Validation Error Message 1",
               "Validation Error Message 2"
           ]
       }
   }
}
3.14.4.1.2. 提出の JSON 定義保存での他のエラー

提出の JSON 定義の保存で予期しないエラーがありました。このイベントは、提出の保存時に発生する可能性のある検証 (例えば、提出のデータベースへの保存時に発生するエラー) 以外の全エラーをカバーします。

{
  type: 'jsonError',
  error: < Error message >
}
3.14.4.1.3. ファイルアップロードのエラー

提出のファイルアップロードでエラーがありました。

{
  type: 'fileUploadError',
  submissionId: < ID of the submission related to the file upload >,
  fileName: < The name of the file uploaded>,
  error: < Error message >
}

3.15. $fh.forms.deregisterListener

注記

お使いの package.jsonfh-mbaas-api のバージョンは、4.8.0 以降である必要があります。

3.15.1. 詳細

$fh.forms クラウド API からリスナーを削除します。

//NodeJS Events Module. Note, this is required to register event emitter objects to forms.
var events = require('events');
var submissionEventListener = new events.EventEmitter();

$fh.forms.registerListener(submissionEventListener, function(err){
  if (err) return handleError(err);

  //submissionEventListener has now been registered with the $fh.forms Cloud API. Any valid Forms Events will now emit.
  submissionEventListener.on('submissionStarted', function(params){
    var submissionId = params.submissionId;
    console.log("Submission with ID " + submissionId + " has started");
  });

  //Removing the listener from the $fh.forms Cloud API.
  $fh.forms.deregisterListener(submissionEventListener);
});

3.16. $fh.forms.exportCSV

注記

お使いの package.jsonfh-mbaas-api のバージョンは、5.10.0 以降である必要があります。

3.16.1. 詳細

CSV ファイルを $fh.forms クラウド API からエクスポートします。エクスポートは、いくつかの CSV ファイルの zip ファイルを返します。フィルターをかけて入力値を使用する際には、以下のフィルターを使用することができます。

  • projectId: フィルターとなるプロジェクトの GUID。
  • submissionId: フィルターとなる単一提出 ID またはそれらのアレイ。
  • formId: フィルターとなる単一フォーム ID またはそれらのアレイ。
  • fieldHeader: エクスポートされる CSV ファイルで使用するヘッダーテキスト。オプションは、フィールド名に使用する name または Form Builder で定義されるフィールドコードを使用する fieldCode
// This is the input parameter to filter the list of CSV files.
var queryParams = {
  projectId: "projectId",
  submissionId: "submissionId",
  formId: ["formId1", "formId2"],
  fieldHeader: "name"
};

$fh.forms.exportCSV(queryParams, function(err, fileStreamObject) {
  // fileStreamObject is a zip file containing CSV files associated
  // to the form it was submitted against.
  if (err) return handleError(err);
  /**
  * Pipe the file stream to a writable stream (for example, a FileWriter)
  */
  fileStreamObject.pipe(writable_stream);
  fileStreamObject.resume();
});

3.17. $fh.forms.exportSinglePDF

注記

お使いの package.jsonfh-mbaas-api のバージョンは、5.12.0 以降である必要があります。

注記

この API は、MBaaS バージョン >=4.1.0 と互換性があります。

3.17.1. 詳細

$fh.forms クラウド API から特定の提出の PDF ファイルをエクスポートします。エクスポートは、ストリームファイルを返します。

var params = {
  submissionId: "submissionId"
};

$fh.forms.exportSinglePDF(params, function(err, fileStreamObject){
  if (err) return handleError(err);
  /**
  * Pipe the file stream to a writable stream (for example, a FileWriter)
  */
  fileStreamObject.pipe(writable_stream);
  fileStreamObject.resume();
});