開発情報・ナレッジ

投稿者: SPIRERS ナレッジ向上チーム 2026年5月22日 (金)

別DBのテキストフィールドをプルダウンで表示する方法

本記事では、テキストフィールドの入力項目を、登録フォーム入力ステップ上にプルダウンで表示するサンプルプログラムです。

ここでは、対象のDBのテキストフィールドをAPIで取得し、プルダウンで表示するサンプルプログラムを紹介いたします。
対象のプルダウンとなるフィールドを登録するDBを、「選択元DB」
登録フォームの元となるDBを「登録先DB」として設定いたします。

DBの設定

今回は以下2つのDBを作成します。
詳しい作成手順は DB機能 をご覧ください。
▼登録先DBフィールド一覧
選択元DBの項目を登録するDBです。
項目名 識別名 フィールドタイプ DB上で必須な属性
テキスト text テキスト なし
▼選択元DBフィールド一覧
選択肢となる値を登録するDBです。
項目名 識別名 フィールドタイプ DB上で必須な属性
選択肢テキスト select_text テキスト なし

ページPHP

※API_URLは、本番環境は https://api.spiral-platform.com/v1(サンプルのとおり)
 エンジニアβ環境は https://api.beta.spiral-platform.net/v1/ ですのでご注意ください。
<?php
//------------------------------
// 設定値
//------------------------------
define("API_URL", "https://api.spiral-platform.com/v1");
define("API_KEY", "xxxxxxxxxxxxxx");
define("APP_ROLE", "");
define("DB_ID", "xxxxx");
define("APP_ID", "xxxxx");

$commonBase = CommonBase::getInstance();

$resultRecordListSelect = $commonBase->apiCurlAction("GET", "/apps/". APP_ID. "/dbs/". DB_ID. "/records");
if(array_key_exists('status', $resultRecordListSelect)){//APIのエラーが発生している場合
    if($resultRecordListSelect["status"] != 200){
        $SPIRAL->setTHValue("APIERROR", $resultRecordListSelect["message"]);//APIのエラーをThymeleafにセット
    }
    }else{
    $text = array();
    foreach($resultRecordListSelect["items"] as $item){ //データを取得
        $text["items"][] = array("text"=>$item["select_text"]);
    }
    $SPIRAL->setTHValues($text); //データをThymeleafにセット
}

//------------------------------
// 共通モジュール
//------------------------------
class CommonBase {
    /**
     * シングルトンインスタンス
     * @var UserManager
     */
    protected static $singleton;

    public function __construct() {
        if (self::$singleton) {
            throw new Exception('must be singleton');
        }
        self::$singleton = $this;
    }
    /**
     * シングルトンインスタンスを返す
     * @return UserManager
     */
    public static function getInstance() {
        if (!self::$singleton) {
            return new CommonBase();
        } else {
            return self::$singleton;
        }
    }
    /**
     * V2用 API送信ロジック
     * @return Result
     */
    function apiCurlAction($method, $addUrlPass, $data = null, $multiPart = null, $jsonDecode = null) {
        $header = array(
            "Authorization:Bearer ". API_KEY,
            "X-Spiral-Api-Version: 1.1",
        );
        if($multiPart) {
            $header = array_merge($header, array($multiPart));
        } else {
            $header = array_merge($header, array("Content-Type:application/json"));
        }
        if(APP_ROLE){
            $header = array_merge($header, array("X-Spiral-App-Role: ".APP_ROLE));
        }
        // curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_URL, API_URL. $addUrlPass);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        if ($method == "POST") {
            if ($multiPart) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            } else {
                curl_setopt($curl, CURLOPT_POSTFIELDS , json_encode($data));
            }
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }
        if ($method == "PATCH") {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }
        if ($method == "DELETE") {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }
        $response = curl_exec($curl);
        if (curl_errno($curl)) echo curl_error($curl);
        curl_close($curl);
        if($jsonDecode){
            return $response;
        }else{
            return json_decode($response, true);
        }
    }
}
?>
            
【編集箇所】
API_KEYの部分には、APIキー
APP_ROLEの部分には、アプリロールの識別名
DB_IDの部分には、選択元DBのDBID
APP_IDの部分には、アプリID
必要に応じて、「select_text」を該当のテキストフィールドの識別名に変更

テキストフィールドソースコードはフォームブロックソースをベースに提供

<!--/* デフォルトブロックソース */-->

<div class="sp-form-container">
  <div class="sp-form-item sp-form-html" th:inline="none"><p><span style="font-size: 18pt;">別DBのテキストフィールドをプルダウンで表示する方法</span></p></div>

  <!--/* サンプルコード */-->

  <!--/* テキスト(text) */-->
  <sp:input-field name="f0xx"></sp:input-field>
  <div class="sp-form-item sp-form-field"> 
  <div class="sp-form-label">
    <th:block>テキスト</th:block>
    <span class="sp-form-required" th:if="${fields['f0xx'].required}" th:text="${fields['f0xx'].requiredIndicator}">*</span>
  </div> 
  <div class="sp-form-data"> 
  <div th:if="${cp.result.isSuccess}">
    <div class="sp-form-dropdown">
        <select class="sp-form-control" th:name="${fields['f0xx'].name}">
          <option value="" selected="selected">----- 選択してください -----</option>
          <option th:each="val : ${cp.result.value['items']}" th:value="${val['text']}" th:text="${val['text']}" th:selected="${val['text']} == ${inputs['f0xx']}">Item</option>
        </select>
        <span class="sp-form-dropdown-icon"></span>
      </div> 
      <p th:text="${cp.result.value['APIERROR']}"></p>
    </div>
    <div th:if="${!cp.result.isSuccess}">
      <p th:text="${cp.result.errorMessage}">error message</p>
    </div>
      <span class="sp-form-noted" th:if="${fields['f0xx'].help != null}" th:text="${fields['f0xx'].help}">Help text</span>
      <span class="sp-form-error" th:if="${errors['f0xx'] != null}" th:text="${errors['f0xx'].message}">Error message</span>
    </div> 
  </div>

  <!--/* デフォルトブロックソース */-->

  <div class="sp-form-item sp-form-interaction">
    <button class="sp-form-prev-button" type="submit" name="action" value="previous" th:if="!${step.isFirst}" th:text="${step.prevButtonLabel}">Prev</button>
    <button class="sp-form-next-button" type="submit" name="action" value="next" th:text="${step.nextButtonLabel}">Next</button>
  </div>
</div>
            
【編集箇所】
f0xのxの部分には、登録先DBのテキストフィールド
APP_ROLEの部分には、アプリロールの識別名
DB_IDの部分には、選択元DBのDBID
APP_IDの部分には、アプリID
必要に応じて、「select_text」を該当のテキストフィールドの識別名に変更

まとめ

本記事では、APIを使用して別DBにあるテキストをプルダウンで表示する方法を紹介しました。
この実装により、別DBの値に応じて、プルダウンの中身を変更し、登録させることが可能です。
DBの項目を追加、APIのレコード一覧の取得の際に、queryを指定することで、
別DBのフィールドが公開の場合のみをプルダウンの中身にするなど、条件指定をすることも可能です。
このサンプルコードをベースに、実際の要件に合わせてカスタマイズしてみてください。

解決しない場合はこちら コンテンツに関しての
要望はこちら