2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google App Maker スプレッドシートをDBにする ~その参 追加~

Last updated at Posted at 2019-01-11

まずはじめに

その壱、その弐を見ている前提です。
Google App Maker スプレッドシートをDBにする ~その壱 表示~
Google App Maker スプレッドシートをDBにする ~その弐 更新~

それでは最後にデータを追加していきましょう。

追加ボタンとフォームの作成

list画面に追加するボタンを配置します。(これはGoogleが用意しているテンプレートから拝借してきましたが、なんでもいいです。)
image.png

PAGE[+] -> Page 適当に名前をつけます。
Page Datasourceはその壱で作ったtestDBを設定します。
image.png

左メニューのウィジェットからFormをドラック&ドロップして配置します。
Choose Datasourcr -> testDB -> NEXT
Edit -> NEXT
Noは自動生成するのでチェックを外し、FINISH
image.png

このままだと入力ができない&初期値が入ってしまうので@Company,@Structure,@Nameを削除します。
image.png

textboxを配置します。
image.png

概ね追加画面は完了ですが、最初に配置したlistの「+」から遷移するように、
Property Editor -> Button -> onClickを選択し、Navigate to Page... -> newを設定します。
image.png

あとはnewで不要なページ遷移ボタンを削除し、BACKボタン、ADDボタンを追加しましょう。
BACKボタンはlistに遷移するようにonClickイベントを設定して下さい。
image.png

一通り画面の作成は終わったので、正常に画面遷移できるか確認してください。

追加処理

ここからはADDボタンをクリックしたときの追加処理を書いていきます。
既にClient ScriptとServer Scriptは作成済みなので書き足していきます。

Client Script

/*
 *追加
 */
function addCell(){
  var addRow = 0;
  var company = app.pages.new.descendants.TextBox1.value;
  var structure = app.pages.new.descendants.TextBox2.value;
  var name = app.pages.new.descendants.TextBox3.value;
  
  var array = [addRow,company, structure, name];
  
  google.script.run.setValue(SPREADSHEET_ID,SHEET_NAME,array);
}

Server Script
前回作成したScriptに//追加の部分を足しました。

/*
 *処理
 */
function setValue(spreadsheetId, sheetName, array){
  var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
  var sheet = spreadsheet.getSheetByName(sheetName);
  var updateRow = Number(array[0]) + 1;
  
  //追加
  if(array[0] === 0){
    var addNo = sheet.getLastRow();
    array[0] = addNo; 
    updateRow = addNo + 1;
  }
  
  for (var i = 0; i < array.length; i++){
    var column = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var range = column.substr(i, 1) + updateRow;
    var cellRange = sheet.getRange(range);
    
    cellRange.setValue(array[i]);
  }
}

ADDボタンのonClickイベントを設定します。

addCell();
app.showPage(app.pages.list);
widget.datasource.load();

動作確認してみます。
image.png
image.png

うん、大丈夫!

・・・と思いきや何度か追加しているとlistに戻っても追加分が反映されない現象になってしまいました。
スプレッドシートでは正常に追加されているのですが・・・

ADDのonClickイベントを少し改良したら改善しました。

createRow();
setTimeout(function(){
  app.showPage(app.pages.list);
  widget.datasource.load();
},1000);

違和感ない程度だしいいかな

まとめ

そんな感じで全3回予定で書いてきたのですが削除も欲しい気がしました。
ここまでやればもうできると思いますが完結させたいという意味で削除も書こうかな・・・

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?