#JP18 Membuat CRUD Data Menggunakan Web Google AppScript

Membuat CRUD Data Menggunakan Web Google AppScript



*Untuk Mendapatkan Full Script tanpa password silahkan Klik Disini*

1. Buatlah Spreadsheet Data

(Bisa copy Spreadsheet Disini)

2. Pada Spreadsheet di atas ada beberapa kolom yang sudah terisi judul yang akan diinput, dan ada 2 sheet yaitu sheet "Data" dan sheet "Provinsi"



3. Buatlah lembar kerja AppScript dengan cara klik menu "Ektensi" lalu pilih "AppScript".


4. Buatlah file dengan klik tanda "+", pastikan file sama persis dan berurutan dengan gambar dibawah ini.
Code.gs
Index.html
JavaScript.html
Form.html
CSS.html
DataTable.html


5. Copy dan pastekan script dibawah ini ke "Code.gs".

Masukkan Password Untuk Melihat Script (Password ada di dalam video)

function doGet(request) {
  return HtmlService.createTemplateFromFile('Index').evaluate();
}


/* DEFINE GLOBAL VARIABLES, CHANGE THESE VARIABLES TO MATCH WITH YOUR SHEET */
function globalVariables(){ 
  var varArray = {
    spreadsheetId   : '1AkWF0EaQT4JJTMBxdML95mr5GwGluMMKT0inociYBIU', //** CHANGE ID SPREADSHEET!!!
    dataRage        : 'Data!A2:G',                                    //** CHANGE !!!
    idRange         : 'Data!A2:A',                                    //** CHANGE !!!
    lastCol         : 'G',                                            //** CHANGE !!!
    insertRange     : 'Data!A1:G1',                                   //** CHANGE !!!
    sheetID         : '0'                                             //** CHANGE !!! 
  };
  return varArray;
}

/*
# PROCESSING FORM ---------------------------------------------------------------------------------
*/


/* PROCESS FORM */
function processForm(formObject){  
  if(formObject.RecId && checkID(formObject.RecId)){//Execute if form passes an ID and if is an existing ID
    updateData(getFormValues(formObject),globalVariables().spreadsheetId,getRangeByID(formObject.RecId)); // Update Data
  }else{ //Execute if form does not pass an ID
    appendData(getFormValues(formObject),globalVariables().spreadsheetId,globalVariables().insertRange); //Append Form Data
  }
  return getLastTenRows();//Return last 10 rows
}


/* GET FORM VALUES AS AN ARRAY */
function getFormValues(formObject){
/* ADD OR REMOVE VARIABLES ACCORDING TO YOUR FORM*/
  if(formObject.RecId && checkID(formObject.RecId)){
    var values = [[formObject.RecId.toString(),
                  formObject.nama,
                  formObject.jeniskelamin,
                  formObject.tanggallahir,
                  formObject.email,
                  formObject.telp,
                  formObject.provinsi]];
  }else{
    var values = [[new Date().getTime().toString(),//https://webapps.stackexchange.com/a/51012/244121
                  formObject.nama,
                  formObject.jeniskelamin,
                  formObject.tanggallahir,
                  formObject.email,
                  formObject.telp,
                  formObject.provinsi]];
  }
  return values;
}


/*
## CURD FUNCTIONS ----------------------------------------------------------------------------------------
*/


/* CREATE/ APPEND DATA */
function appendData(values, spreadsheetId,range){
  var valueRange = Sheets.newRowData();
  valueRange.values = values;
  var appendRequest = Sheets.newAppendCellsRequest();
  appendRequest.sheetID = spreadsheetId;
  appendRequest.rows = valueRange;
  var results = Sheets.Spreadsheets.Values.append(valueRange, spreadsheetId, range,{valueInputOption: "RAW"});
}


/* READ DATA */
function readData(spreadsheetId,range){
  var result = Sheets.Spreadsheets.Values.get(spreadsheetId, range);
  return result.values;
}


/* UPDATE DATA */
function updateData(values,spreadsheetId,range){
  var valueRange = Sheets.newValueRange();
  valueRange.values = values;
  var result = Sheets.Spreadsheets.Values.update(valueRange, spreadsheetId, range, {
  valueInputOption: "RAW"});
}


/*DELETE DATA*/
function deleteData(ID){ 
  //https://developers.google.com/sheets/api/guides/batchupdate
  //https://developers.google.com/sheets/api/samples/rowcolumn#delete_rows_or_columns
  var startIndex = getRowIndexByID(ID);
  
  var deleteRange = {
                      "sheetId"     : globalVariables().sheetID,
                      "dimension"   : "ROWS",
                      "startIndex"  : startIndex,
                      "endIndex"    : startIndex+1
                    }
  
  var deleteRequest= [{"deleteDimension":{"range":deleteRange}}];
  Sheets.Spreadsheets.batchUpdate({"requests": deleteRequest}, globalVariables().spreadsheetId);
  
  return getLastTenRows();//Return last 10 rows
}



/* 
## HELPER FUNCTIONS FOR CRUD OPERATIONS --------------------------------------------------------------
*/ 


/* CHECK FOR EXISTING ID, RETURN BOOLEAN */
function checkID(ID){
  var idList = readData(globalVariables().spreadsheetId,globalVariables().idRange,).reduce(function(a,b){return a.concat(b);});
  return idList.includes(ID);
}


/* GET DATA RANGE A1 NOTATION FOR GIVEN ID */
function getRangeByID(id){
  if(id){
    var idList = readData(globalVariables().spreadsheetId,globalVariables().idRange);
    for(var i=0;i<idList.length;i++){
      if(id==idList[i][0]){
        return 'Data!A'+(i+2)+':'+globalVariables().lastCol+(i+2);
      }
    }
  }
}


/* GET RECORD BY ID */
function getRecordById(id){
  if(id && checkID(id)){
    var result = readData(globalVariables().spreadsheetId,getRangeByID(id));
    return result;
  }
}


/* GET ROW NUMBER FOR GIVEN ID */
function getRowIndexByID(id){
  if(id){
    var idList = readData(globalVariables().spreadsheetId,globalVariables().idRange);
    for(var i=0;i<idList.length;i++){
      if(id==idList[i][0]){
        var rowIndex = parseInt(i+1);
        return rowIndex;
      }
    }
  }
}


/*GET LAST 10 RECORDS */
function getLastTenRows(){
  var lastRow = readData(globalVariables().spreadsheetId,globalVariables().dataRage).length+1;
  if(lastRow<=11){
    var range = globalVariables().dataRage;
  }else{
    var range = 'Data!A'+(lastRow-9)+':'+globalVariables().lastCol;
  }
  var lastTenRows = readData(globalVariables().spreadsheetId,range);
  return lastTenRows;
}


/* GET ALL RECORDS */
function getAllData(){
  var data = readData(globalVariables().spreadsheetId,globalVariables().dataRage);
  return data;
}


/*
## OTHER HELPERS FUNCTIONS ------------------------------------------------------------------------
*/


/*GET DROPDOWN LIST */
function getDropdownList(range){
  var list = readData(globalVariables().spreadsheetId,range);
  return list;
}


/* INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES */
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}



6. Sesuaikan ID Spreadsheet dan Data Range dengan spreadsheet kalian.

.
7. Copy dan pastekan script dibawah ini ke "Index.html".

Masukkan Password Untuk Melihat Script (Password sama dengan di atas)

<!DOCTYPE html>
<html>
    <head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Trirong">
<style>
body {
  font-family: "Trirong", serif;
}
</style>
        <base target="_top">
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
        <?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
        <?!= include('CSS'); ?> <!-- See CSS.html file -->
    </head>
    <body onload="createProvinsiDropdown()">
        <div class="container">
                  <?!= include('Form'); ?> <!-- See Form.html file -->  
                  <hr>
                  <div id="output"></div>
                  <?!= include('DataTable'); ?> <!-- See DataTable.html File -->     
        </div>
    </body>
</html>
<style>.footer,.generic-footer{margin-bottom:98px}@media (min-width:52px){.footer,.generic-footer{margin-bottom:78px}}@media (min-width:52px){.footer,.generic-footer{margin-bottom:56px}}@media (min-width:52px){.footer,.generic-footer{margin-bottom:0}}.disclaimer{position:fixed;z-index:9999999;bottom:0;right:0;border-top:2px solid #ff5c62;text-align:center;font-size:14px;font-weight:400;background-color:#fff;padding:5px 10px 5px 10px}.disclaimer a:hover{text-decoration:underline}@media (min-width:52px){.disclaimer{text-align:right;border-left:2px solid red;border-top-left-radius:10px}}@media (min-width:1920px){.disclaimer{width:20%}}</style><div class="disclaimer">Version.01.05.22 @Copyright <a title="https://www.javabitpro.com/" target="_blank" href="https://www.javabitpro.com/" style="color: black;"><b>www.javabitpro.com</b></a></div>



8. Copy dan pastekan script dibawah ini ke "JavaScript.html".

Masukkan Password Untuk Melihat Script (Password sama dengan di atas)

<style>
#customers {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

#customers td, #customers th {
  border: 1px solid #ddd;
  padding: 8px;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: center;
  background-color: #04AA6D;
  color: white;
}
</style>

<script>
  // Prevent forms from submitting.
  function preventFormSubmit() {
    var forms = document.querySelectorAll('form');
    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
      event.preventDefault();
      });
    }
  }
  window.addEventListener("load", functionInit, true); 
  
  //INITIALIZE FUNCTIONS ONLOAD
  function functionInit(){  
    preventFormSubmit();
    getLastTenRows();
  };      
  
  //HANDLE FORM SUBMISSION
  function handleFormSubmit(formObject) {
    google.script.run.withSuccessHandler(createTable).processForm(formObject);
    document.getElementById("myForm").reset();
  }
  
  //GET LAST 10 ROWS
  function getLastTenRows (){
   google.script.run.withSuccessHandler(createTable).getLastTenRows();
  }
  
  
  //GET ALL DATA
  function getAllData(){
    //document.getElementById('dataTable').innerHTML = "";
    google.script.run.withSuccessHandler(createTable).getAllData();
  }
  
  
  //CREATE THE DATA TABLE
  function createTable(dataArray) {
    if(dataArray){
      var result = "<table id='customers' class='table table-sm' style='font-size:0.8em'>"+
                   "<thead style='white-space: nowrap'>"+
                     "<tr>"+                               //Change table headings to match witht he Google Sheet
                      "<th scope='col'>Delete</th>"+
                      "<th scope='col'>Edit</th>"+
                      "<th scope='col'>ID</th>"+
                      "<th scope='col'>Nama</th>"+
                      "<th scope='col'>Jenis Kelamin</th>"+
                      "<th scope='col'>Tanggal Lahir</th>"+
                      "<th scope='col'>Email</th>"+
                      "<th scope='col'>Telp</th>"+
                      "<th scope='col'>Provinsi</th>"+
                        //Tambah data disini
                    "</tr>"+
                  "</thead>";
      for(var i=0; i<dataArray.length; i++) {
          result += "<tr>";
          result += "<td><button type='button' class='btn btn-danger btn-xs deleteBtn' onclick='deleteData(this);'>Delete</button></td>";
          result += "<td><button type='button' class='btn btn-warning btn-xs editBtn' onclick='editData(this);'>Edit</button></td>";
          for(var j=0; j<dataArray[i].length; j++){
              result += "<td>"+dataArray[i][j]+"</td>";
          }
          result += "</tr>";
      }
      result += "</table>";
      var div = document.getElementById('dataTable');
      div.innerHTML = result;
      document.getElementById("message").innerHTML = "";
    }else{
      var div = document.getElementById('dataTable');
      div.innerHTML = "Data not found!";
    }
  }

  //DELETE DATA
  function deleteData(el) {
    var result = confirm("Want to delete?");
    if (result) {
      var recordId = el.parentNode.parentNode.cells[2].innerHTML;
      google.script.run.withSuccessHandler(createTable).deleteData(recordId);
    }
  }
  
  
  //EDIT DATA
  function editData(el){
    var recordId = el.parentNode.parentNode.cells[2].innerHTML; //https://stackoverflow.com/a/32377357/2391195
    google.script.run.withSuccessHandler(populateForm).getRecordById(recordId);
  }

  //POPULATE FORM
  function populateForm(records){
    document.getElementById('RecId').value = records[0][0];
    document.getElementById('nama').value = records[0][1];
    document.getElementById(records[0][2]).checked = true;
    document.getElementById('tanggallahir').value = records[0][3];
    document.getElementById('email').value = records[0][4];
    document.getElementById('telp').value = records[0][5];
    document.getElementById("provinsi").value = records[0][6];
    //Tambah data disini
    document.getElementById("message").innerHTML = "<div class='alert alert-warning' role='alert'>Update Record [ID: "+records[0][0]+"]</div>";
  }
  
  //RETRIVE DATA FROM GOOGLE SHEET FOR PROVINSI DROPDOWN
  function createProvinsiDropdown() {
      //SUBMIT YOUR DATA RANGE FOR DROPDOWN AS THE PARAMETER
      google.script.run.withSuccessHandler(provinsiDropDown).getDropdownList("Provinsi!A1:A195");
  }
  
  //POPULATE PROVINSI DROPDOWNS
  function provinsiDropDown(values) { //Ref: https://stackoverflow.com/a/53771955/2391195
    var list = document.getElementById('provinsi');   
    for (var i = 0; i < values.length; i++) {
      var option = document.createElement("option");
      option.value = values[i];
      option.text = values[i];
      list.appendChild(option);
    }
  }
</script>



9. Copy dan pastekan script dibawah ini ke "Form.html".

Masukkan Password Untuk Melihat Script (Password sama dengan di atas)

<!-- ## The html code of the form goes here -->
<!-- ## This is included in the Index.html page using "include('Form')" function -->

<form id="myForm" class="form-horizontal" onsubmit="handleFormSubmit(this)"> <!-- Call JavaScript function "handleFormSubmit" -->
    <p class="h4 mb-4 text-center">Input Data</p>
    <div id="message"></div>
    <input type="text" id="RecId" name="RecId" value="" style="display: none">

<!-- ## Nama -->
	<div class="form-group">
		<label for="nama" >Nama</label>
		<input type="text" class="form-control" id="nama" name="nama" placeholder="Nama" required>
	</div>

<!-- ## Jenis Kelamin -->  
	<div class="form-row">
		<div class="form-group col-md-6">
			<p>Jenis Kelamin</p>
			<div class="form-check form-check-inline">
				<input class="form-check-input" type="radio" name="jeniskelamin" id="laki-laki" value="laki-laki">
				<label class="form-check-label" for="laki-laki">Laki-Laki</label>
			</div>
			<div class="form-check form-check-inline">
				<input class="form-check-input" type="radio" name="jeniskelamin" id="perempuan" value="perempuan">
				<label class="form-check-label" for="perempuan">Perempuan</label>
			</div>
		</div>

<!-- ## Tanggal Lahir --> 
		<div class="form-group col-md-6">
			<label for="tanggallahir">Tanggal Lahir</label>
			<input type="date" class="form-control" id="tanggallahir" name="tanggallahir">
		</div>
	</div>

<!-- ## Email --> 
	<div class="form-group">
		<label for="email">Email</label>
		<input type="email" class="form-control" id="email" name="email" placeholder="Email">
	</div>

<!-- ## Nomer Telp --> 
    <div class="form-row">
      <div class="form-group col-md-6">
          <label for="telp">Nomer Telp</label>
          <input type="tel" class="form-control" id="telp" name="telp" placeholder="Nomer Telp">
      </div>

<!-- ## Provinsi --> 
      <div class="form-group col-md-6">
        <label for="exampleFormControlSelect1">Provinsi</label>
        <select class="form-control" id="provinsi" name="provinsi">
          <option>Pilih Provinsi</option>
        </select>
      </div>
		
	
    </div>
	<button type="submit" class="btn btn-primary">Submit</button>
    <input class="btn btn-secondary" type="reset" value="Reset">
</form>



10. Copy dan pastekan script dibawah ini ke "CSS.html".

Masukkan Password Untuk Melihat Script (Password sama dengan di atas)

<style>
.btn-group-xs > .btn, .btn-xs {
  padding: .25rem .4rem;
  font-size: .875rem;
  line-height: .5;
  border-radius: .2rem;
}
</style>



11. Copy dan pastekan script dibawah ini ke "DataTable.html".

Masukkan Password Untuk Melihat Script (Password sama dengan di atas)

<p class="h4 mb-4 text-center">Tabel Database</p>

<div id="dataTable" class="table-responsive">
  <!-- The Data Table is inserted here by JavaScript -->
</div>
<br>
<button type="button" class="btn btn-success btn-sm" onclick="getAllData()">Lihat Semua</button>



12 Tambahkan API Sheet, caranya klik tanda "+" pada Layanan. Scroll kebawah cari "Google Sheet API" klik Tambahkan



13. Klik "Save" , lalu klik "Deploy" pilih "New Deployment".


14. Pastikan type "Web app" dan akses "Anyone". Lalu klik Deploy.


15. Selesai


NB. 
Silahkan tonton tutorial video, cara untuk menambahkan kolom atau isian baru.




Previous Post Next Post

Promo