Oracle JET Webアプリケーションでのデータ・レコードの更新

イントロダクション

このチュートリアルでは、Oracle JavaScript Extension Toolkit (Oracle JET) Webアプリケーションを使用して既存のデータ・レコードを更新し、RESTサービスに送信する方法について説明します。

目的

このチュートリアルの完了時に、既存のデータ・レコードを更新してRESTサービスに送信する方法を学習しました。

前提条件

タスク1:ビューでのダイアログ・ボックスの作成

oj-dialogカスタムHTML要素を使用してフォーム情報を収集し、そこで確認可能に渡します。

  1. JET_Web_Application/src/ts/viewsディレクトリに移動し、エディタでdashboard.htmlファイルを開きます。

  2. oj-button id="createButton"要素を検索し、その下に2つ目のoj-button要素を追加します。on-oj-action属性を"[[showEditDialog]]"に設定し、disabled属性を"[[!itemSelected()]]"に設定します。

    . . .
    <h3 id="itemsListHeader">Activity Items</h3>
     <oj-button id="createButton" on-oj-action="[[showCreateDialog]]">Create</oj-button>
    <!-- If itemSelected is set to false, disabled is true, and vice versa. -->
    <oj-button id="updateButton" disabled="[[!itemSelected()]]" on-oj-action="[[showEditDialog]]">Update
      </oj-button>
    <oj-list-view id="itemsList" class="item-display" data="[[itemsDataProvider]]"
    . . . 
    
  3. oj-bind-if test="[[itemSelected()]]"タグを見つけて、その中にoj-dialog要素を追加します。id属性を"editDialog"class属性をno-displayに設定します。

    . . . 
    <oj-bind-if test="[[itemSelected()]]">
       <oj-dialog id="editDialog" class="no-display" dialog-title="Update Item Details" cancel-behavior="icon">
          </oj-dialog>
    <div id="itemDetailsContainer" class="oj-flex-item oj-panel oj-bg-neutral-30 oj-md-6 oj-sm-12">
       <h3>Item Details</h3>
    . . .
    
  4. 作成したoj-dialog要素内に、2つのdivタグとslot="body"およびslot="footer"属性を追加します。

    <oj-dialog id="editDialog" class="no-display" dialog-title="Update Item Details" cancel-behavior="icon">
    <div slot="body">
      </div>
    <div slot="footer">
      </div>
    </oj-dialog>
    
  5. 作成したdiv slot="footer"要素内にoj-button要素を追加し、on-oj-action="[[updateItemSubmit]]"属性を設定します。

    <div slot="footer">
               <oj-button id="submitBtn" on-oj-action="[[updateItemSubmit]]">Submit
               </oj-button>
             </div>
    
  6. 作成したdiv slot="body"タグ内に、oj-label-valueoj-label要素およびinputItemID値のoj-input-text要素を追加します。

    <div slot="body">
      <oj-label-value label-edge="inside">
       <oj-label for="chatWindow" slot="label">Item ID</oj-label>
       <div slot="value" class="slot-line">
         <oj-bind-text id="chatWindow" value="[[inputItemID]]" class="text-width"></oj-bind-text>
       </div>
     </oj-label-value>
    </div>
    
  7. oj-label-value要素の下に、NamePriceおよびDescription値のoj-input-text要素を追加します。

       
    <div slot="body">
       . . .
       </oj-label-value>
       <oj-label class="oj-label oj-label-value" for="createNewName">Name</oj-label>
       <oj-input-text id="createNewName" value='{{inputItemName}}'></oj-input-text>
       <oj-label class="oj-label oj-label-value" for="createNewPrice">Price</oj-label>
       <oj-input-text id="createNewPrice" value="{{inputPrice}}"></oj-input-text>
       <oj-label class="oj-label oj-label-value" for="createNewDesc">Description</oj-label>
       <oj-input-text id="createNewDesc" value="{{inputShortDesc}}"></oj-input-text>
    </div>
       
    

    inputItemID値は、ユーザーがID値を編集する必要がないため、片方向バインディングを示す大カッコを使用してバインドすることに注意してください。inputItemNameおよびその他の値は、中カッコを使用してバインドします。これは、双方向バインディングを示し、ユーザーが値を上書きできるようにします。

  8. id="itemsList"を持つリスト・ビュー・コンポーネントで、on-first-selected-item-changed属性の値としてselectedItemChangedが指定されていることを確認します。

  9. dashboard.htmlファイルを保存します。

    コードは、このfinal-update-dDashboard-html.txtファイルに似ています。

  10. JET_Web_Application/src/cssディレクトリに移動し、app.cssファイルを開きます。ファイルの末尾に次のスタイル定義を追加します。

    . . .
    .no-display {
       display: none;
    }
    
    .slot-line {
       line-height: 2.4em;
    }
    
    .text-width {
       width: 100%;
       min-width: 100%;
    }
    

    コードは、このfinal-css.txtファイルに似ています。

タスク2: ViewModelでダイアログを開くハンドル

ビューで参照した新しいオブザーバおよびメソッドを宣言して、Oracle JET Webアプリケーションが起動時に正常に初期化されるようにします。

  1. JET_Web_Application/src/ts/viewModelsディレクトリに移動し、エディタでdashboard.tsファイルを開きます。

  2. dashboard.tsファイルの上部で、ダイアログ・コンポーネントおよび入力テキスト・コンポーネントのOracle JETモジュールがインポートされていることを確認します。

    import * as AccUtils from "../accUtils";
    . . .
    import { ojDialog } from "ojs/ojdialog";
    import "ojs/ojdialog";
    import "ojs/ojinputtext";
    . . . 
    
  3. DashboardViewModelクラス内で、新しいアクティビティ・アイテムを作成するための前のコードの下に、showEditDialogというメソッドを作成してダイアログを開き、更新するフィールドの値を取得します。

    . . .
    public createItem = async (event: ojButtonEventMap["ojAction"]) => {
    . . .
     } // end createItem
    
    public showEditDialog = (event: ojButtonEventMap["ojAction"]) => {
    
          this.inputItemName(this.itemData().name);
          this.inputPrice(this.itemData().price);
          this.inputShortDesc(this.itemData().short_desc);
    
       (document.getElementById("editDialog") as ojDialog).open();
     }     
    
  4. showEditDialogメソッドの下で、updateItemSubmitというメソッドを作成してダイアログ・データを送信し、closeコマンドを追加します。

    public showEditDialog = (event: ojButtonEventMap["ojAction"]) => {
    
          this.inputItemName(this.itemData().name);
          this.inputPrice(this.itemData().price);
          this.inputShortDesc(this.itemData().short_desc);
    
       (document.getElementById("editDialog") as ojDialog).open();
     }     
    
    public updateItemSubmit = async (event: ojButtonEventMap["ojAction"]) => {
       (document.getElementById("editDialog") as ojDialog).close();
    }  
    
  5. dashboard.tsファイルを保存します。コードは、この update-dashboard-ts.txtファイルのようになります。

タスク3: ViewModelでのダイアログ入力の送信の処理

ビューのダイアログからフェッチしたデータを保持するオブジェクトを作成し、フェッチAPIおよびHTTP PUTメソッドを使用してRESTサービスに送信します。最後に、RESTDataProviderインスタンスでRESTDataProvidermutateメソッドを使用します。

  1. 開いているdashboard.tsファイルのDashboardViewModelクラスで、データを送信する方法で使用する次の変数の型を宣言し、初期化します。

    class DashboardViewModel {
       . . .
       // Fields in update dialog
       inputItemID: ko.Observable<number>;
       inputItemName: ko.Observable<string>;
       inputPrice: ko.Observable<number>;
       inputShortDesc: ko.Observable<string>; 
    
       //  Fields for delete button and update dialog, among others
       selectedRow = ko.observable<number>();
       . . .
    
       constructor() {
       . . .
          // Initialize fields in update dialog
          this.inputItemID = ko.observable();
          this.inputItemName = ko.observable();
          this.inputPrice = ko.observable();
          this.inputShortDesc = ko.observable();
    
       } // End constructor
    
  2. close()コールの上にあるupdateItemSubmitメソッドで、変数rowを宣言して、「アイテム詳細の更新」ダイアログからの入力値を保持します。また、データが選択されていることを確認するif文も含まれます。

    public updateItemSubmit = async (event: ojButtonEventMap["ojAction"]) => {
        const currentRow = this.selectedRow; 
             if (currentRow != null) {
                const row = {
                   itemId: this.itemData().id,
                   name: this.inputItemName(),
                   price: this.inputPrice(),
                   short_desc: this.inputShortDesc()
                };
       }; // End if statement
     (document.getElementById("editDialog") as ojDialog).close();
    }  
    
  3. close()コールの上に、データをRESTサービスに送信するリクエストを作成します。

    public updateItemSubmit = async (event: ojButtonEventMap["ojAction"]) => {
    
     const currentRow = this.selectedRow;
    
     if (currentRow != null) {
    
       const row = {
       	. . .
          short_desc: this.inputShortDesc()
       };
    
    // Create and send request to update row on rest service
       const request = new Request(
    
         `${this.restServerURLItems}${this.itemData().id}`,
         {
           headers: new Headers({
             "Content-type": "application/json; charset=UTF-8",
           }),
           body: JSON.stringify(row),
           method: "PUT",
         }
       );
       const response = await fetch(request);
       const updatedRow = await response.json();  
     } // End if statement
     (document.getElementById("editDialog") as ojDialog).close();
    
    }  // update-item-end
    
  4. RESTサービスへのデータの送信リクエストの下で、update mutateを作成し、mutateメソッドをコールして、データが更新されたことをRESTDataProviderインスタンスに通知します。また、refresh()メソッドをコールして、ブラウザに表示されるデータをリフレッシュします。

    public updateItemSubmit = async (event: ojButtonEventMap["ojAction"]) => {
    
    const currentRow = this.selectedRow; 
    
       if (currentRow != null) {
          . . .
    
       };
    
       const request = new Request(
    
       `${this.restServerURLItems}${this.itemData().id}`,
          {
             . . .
          }
          );
    
    . . . 
       const updatedRow = await response.json();
       // Create update mutate event and call mutate method
       // to notify dataprovider consumers that a row has been
       // updated
       const updatedRowKey = this.itemData().id;
       const updatedRowMetaData = { key: updatedRowKey };
       this.itemsDataProvider.mutate({
       update: {
          data: [updatedRow.items[0]],
          keys: new Set([updatedRowKey]),
          metadata: [updatedRowMetaData],
       },
       });
       this.itemsDataProvider.refresh();
    
       } // End if statement
       (document.getElementById("editDialog") as ojDialog).close();
    }  // update-item-end
    
  5. dashboard.tsファイルを保存します。

    コードは、このfinal-update-dashboard-ts.txtファイルに似ています。

タスク4:コードのテストとレコードの更新

  1. ブラウザで、Webアプリケーションの動的な変更を表示します。

  2. Webアプリケーションで、「ベースボール」アクティビティをクリックし、SureFireボール(4のセット)項目をクリックします。

  3. 「更新」ボタンをクリックします。

    「アイテム詳細の更新」ダイアログ・ボックスが表示されます。

  4. 価格を20.5から21に変更し、「送信」をクリックします。

    セクションがリフレッシュされ、品目の価格が更新されました。

    品目詳細の更新

    図update_record.pngの説明

  5. 実行中のWebアプリケーションを表示するブラウザ・ウィンドウまたはタブを閉じます。

  6. 端末ウィンドウでCtrl+Cを押し、プロンプトが表示されたらyと入力してOracle JETツール・バッチ・ジョブを終了します。

その他の学習リソース

docs.oracle.com/learnの他のラボを調べるか、Oracle Learning YouTubeチャネルでさらに無料の学習コンテンツにアクセスします。さらに、education.oracle.com/learning-explorerにアクセスしてOracle Learning Explorerにします。

製品ドキュメントは、Oracleヘルプ・センターを参照してください。