Negana to, kad google spreadsheet jau savaime yra puikus įrankis. Jį dar galima panaudoti ir (formos) duomenų saugojimui.
Kodėl tai naudinga? Priežasčių daug:
- duomenų bazė su patogiu administravimu
- atsarginė duomenų kopija (pvz jei formos duomenys siunčiami tik el.paštu, visada liks ir kopija google spreadsheet dokumente)
- Galimybė “prenumeruoti” pasikeitimus (gauti laišką, kai pasikeičia duomenys)
- Nereikalauja didelių kodo modifikacijų interneto svetainėje
- Galima lengvai kontroliuoti kas pasiekia informaciją (t.y. dalintis dokumentu su darbuotojais)
- ir kt.
Kitaip tariant jei turite pvz.: kontaktinę formą ir joje įvestus duomenis gaunate el. paštu tik Jūs vienas. Gal ir nėra būtinybės papildomai saugoti šios formos duomenų kažkur internete ar duomenų bazėje. Bet jei formų informacija yra kažkiek svarbi ir vyksta tik duomenų siuntimas el. paštų tada tikrai rekomenduočiau apsvarstyti kažkokį papildomą duomenų išsaugojimo variantą.
Ka gi, o dabar prie reikalo. Sakykime norėsim saugoti kontaktinės formos duomenis, kurioje lankytojas įves savo vardą, el. paštą ir komentarą.
1. Sukuriam naują google spreadsheet dokumentą.
2. Einam Tools > Script Editor ir sukuriam naują Blank Project. Sugalvojam jam pavadinimą ir code.gs lange įkeliam:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
// 1. Enter sheet name where data is to be written below var SHEET_NAME = "Sheet1"; // 2. Run > setup // // 3. Publish > Deploy as web app // - enter Project Version name and click 'Save New Version' // - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously) // // 4. Copy the 'Current web app URL' and post this in your form/script action // // 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case) var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service // If you don't want to expose either GET or POST methods you can comment out the appropriate function function doGet(e){ return handleResponse(e); } function doPost(e){ return handleResponse(e); } function handleResponse(e) { // shortly after my original solution Google announced the LockService[1] // this prevents concurrent access overwritting data // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html // we want a public lock, one that locks for all invocations var lock = LockService.getPublicLock(); lock.waitLock(30000); // wait 30 seconds before conceding defeat. try { // next set where we write the data - you could write to multiple/alternate destinations var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key")); var sheet = doc.getSheetByName(SHEET_NAME); // we'll assume header is in row 1 but you can override with header_row in GET/POST data var headRow = e.parameter.header_row || 1; var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var nextRow = sheet.getLastRow()+1; // get next row var row = []; // loop through the header columns for (i in headers){ if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column row.push(new Date()); } else { // else use header name to get data row.push(e.parameter[headers[i]]); } } // more efficient to set values as [][] array than individually sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // return json success results return ContentService .createTextOutput(JSON.stringify({"result":"success", "row": nextRow})) .setMimeType(ContentService.MimeType.JSON); } catch(e){ // if error return this return ContentService .createTextOutput(JSON.stringify({"result":"error", "error": e})) .setMimeType(ContentService.MimeType.JSON); } finally { //release lock lock.releaseLock(); } } function setup() { var doc = SpreadsheetApp.getActiveSpreadsheet(); SCRIPT_PROP.setProperty("key", doc.getId()); } |
3. Spaudžiam Publish > Deploy as web app.. ir atsidariusiame lange nurodom
Po “Deploy” patvirtinam kruvele pranešimų apie saugumą ir Jums sugeneruojamas URL. Mano atveju šis url:
https://script.google.com/macros/s/AKfycbyRs2qfvz5-qmhyFPVmpm0hayjcofsDIcnypkb_Zz0fDzriMWAb/exec
Prieš naudojant šią nuorodą dar paspauskite Run > Setup
jei nuoroda veikianti ją įkėlus į interneto naršyklę pamatysite {"result":"success","row":3} panašų pranešimą.
Ka gi, pagrindinis darbas atliktas, turim nuorodą į kurią siunčiant formos duomenis jie bus išsaugoti spreadsheete. Nepamirškite, kad spreadsheeto pirmoji eilutė tai formos laukų pavadinimai, be to svarbios ir didžiosios ar mažosios raidės, tarpai.
4. Pats paprasčiausias formos išsaugojimo būdas.
Sukuriam paprastą html formą:
1 2 3 4 5 6 7 8 9 |
<form id="form" action="https://script.google.com/macros/s/AKfycbyRs2qfvz5-qmhyFPVmpm0hayjcofsDIcnypkb_Zz0fDzriMWAb/exec"> <label>Vardas</label><br /> <input name="Vardas" type="text" value="" /><br /> <label>El. paštas</label><br /> <input name="El_pastas" type="text" value="" /><br /> <label>Komentaras</label><br /> <textarea name="Komentaras"></textarea><br /> <input type="submit" value="Siųsti" /> </form> |
aišku toks būdas labiau teorinis, nes turbūt nenorėsite lankytojui rodyti result pranešimo po formos išsiuntimo, todėl įkelsiu pilną korektiškai veikiančios formos pavizdį.
5. Pilnas formos išsaugojimo pavizdys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<html> <head> <title>Saugojam formos duomenis į google spreadsheet</title> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#form").submit(function(event){ // Variable to hd request var request; // Bind to the submit event of our form // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("input, select, button, textarea"); // Serialize the data in the form var serializedData = $form.serialize(); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); jQuery.support.cors = true; console.log(serializedData) request = $.ajax({ type: "POST", url: "https://script.google.com/macros/s/AKfycbyRs2qfvz5-qmhyFPVmpm0hayjcofsDIcnypkb_Zz0fDzriMWAb/exec", cache: false, data: serializedData, dataType : 'json', crossDomain:true, }); // Callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); // Prevent default posting of form event.preventDefault(); }); }); </script> </head> <body> <form id="form"> <label>Vardas</label><br /> <input name="Vardas" type="text" value="" /><br /> <label>El. paštas</label><br /> <input name="El_pastas" type="text" value="" /><br /> <label>Komentaras</label><br /> <textarea name="Komentaras"></textarea><br /> <input type="submit" value="Siųsti" /> </form> </body> </html> |
Koncepcija čia paprasta, perimamas formos siuntimas, serealizuojami formos duomenis ir siunčiami tiesiai kur reikia, siuntimo metu forma tampa neaktyvi, o po siuntimo vėl aktivuojama.
Nepamirškite užkomentuoti nereikalingų
console.log(); jie buvo palikti testuojant.
Kartais verta apsvarstyti ir kiek egzotiškesnius duomenų saugojimo būdus, kurie gali būti patogesni klientui paprasčiau administruojami ar intuityvesni. Tikiuosi, kad mano pasiūlytas variantas Jums bus naudingas.