本記事では、updateCellを使用して、数量や単価を編集した際に、合計金額を自動で再計算して表示する方法を解説します。

IgrGrid の設定

IgrGrid のupdateCellメソッドを利用すると、任意の行・列のセルを直接更新することができます。
以下の例では、数量 (quantity) または単価 (unitPrice) を編集すると、対応する行の合計金額 (total) を再計算し、updateCellによって UI に反映します。

<IgrGrid
  ref={gridRef}
  data={sampleData}
  cellEditDone={onCellEditDone}
  primaryKey="id"
  width="100%"
  height="300px"
>
  <IgrColumn field="product" header="Product" />
  <IgrColumn field="quantity" header="Quantity" dataType="number" editable={true} />
  <IgrColumn field="unitPrice" header="Unit Price" dataType="number" editable={true} />
  <IgrColumn field="total" header="Total" dataType="number" editable={false} />
</IgrGrid>

updateCell の使用

ここでは、セルの編集完了イベント (cellEditDone) をフックして、編集された値をもとに計算を行い、updateCell を使って合計セルを更新します。
編集イベントからは以下のように情報が取得できます:

  • e.detail.column.field:編集された列名
  • e.detail.rowID:編集された行のID
  • e.detail.newValue:新しい値
// グリッドコンポーネントへの参照を作成
const gridRef = useRef<IgrGrid>(null);

// セル編集完了時のイベントハンドラ
const onCellEditDone = (s: IgrGridBaseDirective, e: IgrGridEditDoneEventArgs) => {
  // 編集された列名(フィールド)を取得します
  const field = e.detail.column.field;
  // 編集された行の ID を取得します
  const rowID = e.detail.rowID;

  // グリッド参照がなければ何もしません
  if (!gridRef.current) return;

  // 「quantity」または「unitPrice」列が編集された場合のみ処理を行います
  if (field === "quantity" || field === "unitPrice") {
    // 編集された行のデータを取得します
    const rowData = gridRef.current.data.find((item: any) => item.id === rowID);
    if (!rowData) return;

    // 編集されたフィールドは新しい値、それ以外は既存値を使用します
    const quantity = Number(field === "quantity" ? e.detail.newValue : rowData.quantity);
    const unitPrice = Number(field === "unitPrice" ? e.detail.newValue : rowData.unitPrice);

    // 合計値を計算します
    const total = quantity * unitPrice;
    // 合計セルを更新します
    gridRef.current.updateCell(total, rowID, "total");
  }
};

実行結果

この設定を適用すると、IgrGrid の「合計」列は以下のように動作します。

ダウンロード後、以下のコマンドで実行できます。

npm ci
npm run dev
Tagged: