Store persistent HTML form data in Google Script - google-apps-script

I wrote a Google Script web app to back up selected Gmail labels to a user-defined Google Drive location. Forml.html presents the data in a tabular format. On each row lives index (which is the checkbox), label and drive target.
We would like the data in each row to persist from one page load to the next so that a selected row stays selected. After I figure out how to make the data persist, then I can build a trigger which will make the app run on a schedule and back up the selected labels. Any thoughts on how best to achieve the effect of storing HTML form data over time? I'm thinking of using the properties service, but I don't know how I can change the initial doGet to choose between a blank form and a form with preexisting data.
Form.html
<div id="formDiv">
<form id="myForm" target="_self">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">
<h3 span style="font-family:arial,helvetica,sans-serif;">Select</span></th>
<th scope="col">
<h3 span style="font-family:arial,helvetica,sans-serif;">Label</span></th>
<th scope="col">
<h3 span style="font-family:arial,helvetica,sans-serif;">Drive target</span></th>
</tr>
</thead>
<tbody>
<? var label = GmailApp.getUserLabels();
for (i = 0; i < label.length; i++) { ?>
<tr>
<td style="text-align: center;">
<span style="font-family:arial,helvetica,sans-serif;"><input id="index" type="checkbox" name="index" value="<?= [i]; ?>" /></span></td>
<td>
<span style="font-family:arial,helvetica,sans-serif;"><input id="label" type="text" style="border:none" size="60" name="label" value="<?= label[i].getName(); ?>" readonly /></span></td>
<td>
<span style="font-family:arial,helvetica,sans-serif;">Gmail Backup/<input id="target" type="text" size="60" maxlength="128" name="target" value="<?= label[i].getName(); ?>" /></span></td>
</tr>
<? } ?>
</tbody>
</table>
<p><input type="submit" value="Test" onclick="google.script.run.gmailBackup(this.parentNode.parentNode)" />
</p>
</form>
</div>
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile("Form")
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return template;
}
function gmailBackup(template) {
// Set HTML form variables
var indices = template.index;
var labels = template.label;
var targets = template.target;
for (i = 0; i < indices.length; i++) {
var index = indices[i].toString();
var label = labels[indices[i]].toString();
var target = "Gmail Backup/" + targets[indices[i]].toString();
...
}

I ended up using the PropertiesService to store HTML form properties on a per-user basis. This looks like it will work quite well (especially once I find out exactly where the data is stored per Where does Google Script PropertiesService store data?).
From Form.html
<input onclick="google.script.run.setProperties(this.parentNode.parentNode);" type="submit" value="Save" >
From Code.gs
function setProperties(form) {
var filledForm = PropertiesService.getUserProperties().setProperty("FORM", form);
}

Related

Laravel add row to table without refreshing page

I'm trying to add row to the table without refreshing page is it possible without using js? Basically I have a table and input in the modal my problem is that I need to refresh the page whenever I'm adding data to table which closes modal and data from the table has to be saved only when pressing save button in the modal. Maybe it is possible to do that using Laravel Controllers?
<table class="table" style="margin-top: 16px">
<tbody>
<tr>
<td class="table-text">
<div style="float: left">TASK NAME</div>
</td>
<td style="width: 10%">
<div style="float: end">DELETE</div>
</td>
</tr>
</tbody>
This is not possible without javascript.
Assuming you are using jquery, I would do something like this:
$('form').on('submit', function(e) {
e.preventDefault(); // Disable the sending of the form
var one = $('#one').val();
var two = $('#two').val();
$('#one').val('');
$('#two').val('');
$.ajax({
url: "/api/products/add",
method: 'post',
data: {
product: one,
price: two
},
success: function(){
appendToTable(one, two);
}
});
appendToTable(one, two); // The Success function in this ajax would never reach, because the url is not set. Thats because the function is called here.
});
function appendToTable(one, two) {
$('table').append(`
<tr>
<td>${one}</td>
<td>${two}</td>
</tr>
`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/api/products/add" method="post">
<input id="one" name="product" type="text" placeholder="product" required>
<input id="two" name="price" type="number" placeholder="price" required>
<button>Add</button>
</form>
<table>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>PC</td>
<td>500</td>
</tr>
</table>
You disable the forms default behavior (submitting) and do the nessesarry work with js (or jquery). If the user hover disables js, the form submits as normal and sends the data.

Create a variable if checkbox is checked and write it back to Google spreadsheet

I am trying to create variable if a checkbox is checked in a HTML form.
But could not succeed to write it back.
Here is my complete HTML code "Index.html":-
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<br>
<h1>Add Row To Spreadsheet</h1><br />
<form id='myForm'>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td></td>
<td><input type="checkbox" name="name1" id="name1"/>A</td>
<td><input type="checkbox" name="name2" id="name2"/>B</td>
<td><input type="checkbox" name="name3" id="name3"/>C</td>
<td><input type="checkbox" name="name4" id="name4"/>D</td>
</tr>
<input type="button" value="Submit" onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.itemAdd(this.parentNode)" />
</table>
<br>
</form>
</html>
Mentioned below is my "Code.gs:-
function openInputDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Item');
}
function itemAdd(form)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var lastRow = sheet.getLastRow();
var match1 = sheet.getRange("B2").getValue();
var dataRange = sheet.getRange(1, 1,lastRow).getValues();
for(var i=0;i<dataRange.length;i++)
{
if(dataRange[i][0] == match1)
{
if(document.getElementById("name1").checked)
{
days="yes";
sheet.getRange(i+1, 2).setValue(days)
}
}
}
}
Any Help is appreciated, I think html is complete but I am missing something in code.gs Kindly lt me know if you need any further clarification.
Your example should show your form element and submit button in order to verify that you are passing the form element correctly to your google apps script function.
itemAdd() is running on the server side, so it does not have access to DOM elements such as document.getElementById(). You need to access your value of interest from the form element.
Your checkbox elements need to have a value assigned to them
<input type="checkbox" name="name1" id="name1" value="name1val"/>
Your call to itemAdd should pass the form element
.itemAdd(document.getElementById('myForm'));
Once this is done, you should see your form values. You can inspect this by adding the following code.
Logger.log(form)
I believe that the following will provide to access your value.
form["name1"]

Simple Checkbox values to SQL database

Sorry for asking something that seems to have been asked many times, but is because I'd not found anything so... simple as my case, so I'm not so sure about that path to follow.
The thing is, I have a form, in the page "estimate.php" with most of its input types as Text, and some checkboxes. Its action is set to "insert.php", where is the code that sends the e-mail, and sends the data to the database, and on the end of it, an alert and a redirection to the form page.
When I fill the form without checking anything on the checkboxes, everything works just fine, the database columns are filled perfectly, and the e-mail is correctly sent, the fields that were supposed to receive the checkboxes values are blank, as it was supposed to be, since I've not filled them. But once I try to use the checkboxes, when I hit Submit, I get a empty page, and the address freezes on insert.php. I'm not sure what is happening, but since I haven't worked with Checkbox to SQL before, and I'm pretty newbie on coding, I think it has something to do with the way I'm trying to process the data from the checkboxes to send it to the db. I understood that, setting values to each checkbox, it would post them as text.
Here are the codes (the most important parts of if, to try to summarize. [...] are in place of parts I took away, to make it more simple for you to help me.)
-
FORM:
<form id="contact-form" action="../painel/insert.php" method="POST">
//[...]
<div style="margin-top: 20px;">
<p style="margin-bottom: 0;">Quantidade de pares por numeração</p>
<br />
<div class="table-responsive">
<table class="table table-bordered">
<tr>SANDÁLIAS INFANTIS</tr>
<thead>
<tr>
<th class="text-center">Numeração</th>
<th class="text-center">Quantidade</th>
<th class="text-center">Alça</th>
</tr>
</thead>
<tbody>
<tr>
<td>25/26</td>
<td><input type="text" name="i2526_quant"></td>
<td style="text-align: left;">
<input type="checkbox" name="i2526_a" value="Slim"> Slim<br>
<input type="checkbox" name="i2526_a" value="Tradicional"> Tradicional
</td>
</tr>
<tr>
<td>27/28</td>
<td><input type="text" name="i2728_quant"></td>
<td style="text-align: left;">
<input type="checkbox" name="i2728_a" value="Slim"> Slim<br>
<input type="checkbox" name="i2728_a" value="Tradicional"> Tradicional
</td>
</tr>
<tr>
<td>29/30</td>
<td><input type="text" name="i2930_quant"></td>
<td style="text-align: left;">
<input type="checkbox" name="i2930_a" value="Slim"> Slim<br>
<input type="checkbox" name="i2930_a" value="Tradicional"> Tradicional
</td>
</tr>
<tr>
<td>31/32</td>
<td><input type="text" name="i3132_quant"></td>
<td style="text-align: left;">
<input type="checkbox" name="i3132_a" value="Slim"> Slim<br>
<input type="checkbox" name="i3132_a" value="Tradicional"> Tradicional
</td>
</tr>
</tbody>
</table>
</div>
//[...]
<input type="submit" class="submit no-margin-bottom" value="Enviar" style="font-size:20 px; padding: 10px; border: 3px solid #555555;"/>
</form>
-
THE CODE, on Insert.php:
<?php
include "conexao.php";
//[...]
$i2526_quant = $_POST['i2526_quant'];
$i2526_a = $_POST['i2526_a'];
$i2728_quant = $_POST['i2728_quant'];
$i2728_a = $_POST['i2728_a'];
$i2930_quant = $_POST['i2930_quant'];
$i2930_a = $_POST['i2930_a'];
$i3132_quant = $_POST['i3132_quant'];
$i3132_a = $_POST['i3132_a'];
//[...]
$inserir = "INSERT INTO orcamento VALUES([...],'$i2526_quant','$i2526_a','$i2728_quant','$i2728_a','$i2930_quant','$i2930_a','$i3132_quant','$i3132_a',[...])";
//[...](here is the part of the code that sends the e-mail. As I said, everything is working fine, except for the checkboxes (actually, I took away the part from the code that would send the checkbox values to the e-mail and tested it again, and it didn't work. Since the code is pretty long, I decided not to post it (if you need to, I will).
$enviado = $mail->Send();
if ($enviado) {
//$envia = mail($recipient, $subject, $message, $headers);
echo '<script>alert("Obrigado! Orcamento enviado com sucesso, responderemos o mais breve possível.");location="../estimate.php";</script>';
}else{
echo '<script>alert("Erro ao enviar orcamento.");location="../estimate.php";</script>';
} }
?>
--
Thank you very much in advance. I'm sorry for the poor english, and for being such a newbie, as I'm pretty sure this is a simple thing to solve, but hey, here I am trying to learn from the bests (:
Try to add [] after the checkbox name in your HTML file. This will post them as an array to your PHP file. If you don't do that there is no possibility to have several checked values.
Not sure if this solves your error. You should be able to get more information though by adding the following to the top of your insert.php file:
error_reporting = E_ALL;
ini_set('display_errors', 'On');
This enables error reporting for the file and should output what's going wrong. Make sure to remove that after fixing your error.

how to pass value of checkboxes using ahref

I am using following code in my project
<cfoutput query="getOptions">
<tr>
<td align="center"> #optionname#</td>
<td align="center"> #DollarFormat(optionprice)#</td>
<td><input type="checkbox" name="OptionalID" value="#OptionID#" ></td>
</tr>
</cfoutput>
And i am passing the value to other form as follows
<a href="addtocart.cfm?pid=#productId#&OptionalID=#OptionalID#">
what should i do to pass all values of all the checkboxes that are checked.Please help
Thanks in advance
Change your page to use a form instead of passing the values via a link.
Something along the lines of:
<form name="myform" action="addToCart.cfm" method="post">
<cfoutput>
<input type="hidden name="pid" value="#productId#">
<input type="hidden name="OptionalID" value="#OptionalID#">
<cfloop query="getOptions">
<tr>
<td align="center"> #optionname#</td>
<td align="center"> #DollarFormat(optionprice)#</td>
<td><input type="checkbox" name="OptionalID" value="#OptionID#"></td>
</tr>
</cfloop>
<input type="submit" value="Add to cart">
</cfoutput>
</form>
You can pass as many values as you want now, and the checkboxes will come up as a list.
hope that helps
Though you can get tricky with JavaScript, if you use an A to add to cart, you'll only be passing the values in the URL. You want to use a form instead.
<form name="cartForm" action="addtocart.cfm?pid=#productId#&OptionalID=#OptionalID#" method="POST">
. . . .
</form>
Of course, this means you'd ordinarily use a submit button inside your form. If you're set on using a link, you can do
Add to cart
(note that I've omitted various tags and escaping of # for simplicity)
You need JavaScript for that.
First, have this in your page where you have the code you posted:
<script type="text/javascript">
function AddCheckboxValues(oLink, sName) {
var arrCheckboxes = document.getElementsByName(sName);
var values = [];
for (var i = 0; i < arrCheckboxes.length; i++) {
if (arrCheckboxes[i].checked) {
values.push(arrCheckboxes[i].value);
}
}
oLink.href += "&" + sName + "=" + values.join(",");
}
</script>
Second, add onclick to the link tag:
<a href="addtocart.cfm?pid=#productId#" onclick="AddCheckboxValues(this, 'OptionalID');">
That's it, now the form addtocart.cfm will get query string values of the checkboxes ticked by the user.

form>table (ajax)>form

I want to do different action for each submit button. For example compare will go to "compare.php" and delete will go to "test.php". I know i can't do form inside form but i can't separate to two forms because this is one table. I thought maybe to do
<?php if(isset($_POST["com"])){ javascript - link to compare.php}?>
but how can i send the _POST to this page?
I also thought on send the ind as _GET but the user can select more then one (two deletes or two compares)
of course if you have other solutions..
<html>
<head>
<script>
build ajax tbody...
for (i = 1; i <= numOfRows; i++)
{
oCell = oRow.insertCell(-1);
oCell.innerHTML = "<input type='checkbox' value='"+ ind + "'name='com[]'>";
oCell = oRow.insertCell(-1);
oCell.innerHTML = "<input type='checkbox' value='"+ ind + "'name='del[]' ;>";
.....
</script>
<body>
<form method="post" action="test.php">
<table>
<thead>
<tr>
<th><input type="submit" value="Compare" /></th>
<th><input type="submit" value="Delete" /></th>
</tr>
</thead>
<tbody></tdbody>
</table>
</form>
</body>
</html>
Thank you!
You can simply have:
<input type="submit" value="Compare" onclick="this.form.action = 'someotherpage.php';" />
This will change the form action upon clicking the submit button.