Create dropdown menu within a popup window - google-apps-script

I have a list of records in multiple sheets (same workbook).
I currently have a dropdown menu within my googlesheet where if you select one of the records it will delete the row with that record.
However, I would like to give the option to either move it to another sheet or delete it. I was trying to use UiApp but then found out alot of the options are deprecated and that now I have to use HTMLService.
So what I'm looking to do is, once I select a record, have a popup that has two options.
Option 1 : a Move option (button) with a dropdown of the names of the other sheets within the workbook that will then move that record to that sheet
Option 2 : Delete the record
Option 3 : Cancel.
Is this possible? and if so, would someone be able to guide me to the right direction or a similar example so I can try and figure out how to get that going?

You can try creating a Custom dialogs
A custom dialog can display an HTML service user interface inside a Google Docs, Sheets, or Forms editor.
Custom dialogs do not suspend the server-side script while the dialog is open. The client-side component can make asynchronous calls to the server-side script using either the google.script API for HTML-service interfaces or server handlers for UI-service interfaces.
Code.gs
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Custom Menu')
.addItem('Show dialog', 'showDialog')
.addToUi();
}
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'My custom dialog');
}
Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select>
<option>Delete</option>
<option>Move</option>
</select>
</body>
</html>
With that, try reading about HTML Service: Communicate with Server Functions
google.script.run is an asynchronous client-side JavaScript API that allows HTML-service pages to call server-side Apps Script functions. The following example shows the most basic functionality of google.script.run — calling a function on the server from client-side JavaScript.
Here is a sample code for form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<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', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input name="myFile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
Hope this helps!

Related

How can I add a horizontal scrollbar in the google sheet similar to form control scrollbar in excel?

I would like to add a horizontal scrollbar that will provide the values 0-365 based on its position and use this value for calculation.
I am creating a Gantt chart, the same as is on the page https://www.vertex42.com/ExcelTemplates/excel-gantt-chart.html
There is a horizontal scrollbar that helps "to move" with the calendar.
I have put there a number that I must change manually. I haven't found any solution on the internet.
This kind of control is simply not available natively within Google Sheets. I found a recent response from the Google Support Forums to indicate this is still the case.
If you want to build this functionality out yourself, it is actually now possible to do so, by taking full advantage of the Apps Script platform and their Google Sheets and HTML Service scripting APIs. You can create a dialog box with HTML and JS, which can have any inputs you want, including range sliders, and it can send the values back to the Google Sheet script, which can then save it to a cell. I put together a barebones test to make sure it would work, and it does:
I used Menu -> Tools -> Script Editor, and then created these two files:
Code.gs:
// Trigger dialog to be added to menu on file open
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi()
.showModalDialog(html, 'Dialog title');
}
function saveSliderVal(updatedVal){
var sheetToSaveTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Gantt');
if (!sheetToSaveTo){
sheetToSaveTo = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
}
var cellToSaveTo = sheetToSaveTo.getRange('A1:A1');
cellToSaveTo.setValue(updatedVal);
}
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function update() {
document.getElementById('val').innerText = document.getElementById('input').value;
}
function save() {
// Call sheet function
google.script.run.saveSliderVal(parseInt(document.getElementById('input').value, 10));
}
</script>
<input id="input" type="range" min="0" max="365" onchange="update()" oninput="update()" value="0"
step="1" />&nbsp<span id="val">0</span>
<br />
<button id="save" onclick="save()">Save to Gantt</button>
</body>
</html>
Then reload the sheet after saving your script, and you should see Dialog -> Open as a new menu item. Clicking it will bring up your custom HTML.

Control Flow Between Server and Client and Back to Server for Google Apps Script

I have a question about the control flow between some JavaScript code running as bound functions within a google spreadsheet - so server side - and a dialog (that happens to be Modal, but Modeless is the same) that is client side.
While the code examples below work fine in that the dialog successfully calls the server side function as per the line below, and the withSuccessHandler works too.
google.script.run.withSuccessHandler(success_callback).getCredentials(this.parentNode)
But what I actually want to achieve is for some server side code to carry on executing once the dialog has gone; ideally from the point the .showModalDialog() function was called, but I'd be happy just passing control back to any server-side function.
Some example software is below; don't forget this works, just not how I want it too! Essentially the event handler for a menu item created by the the OnOpen() function calls a modal dialog to prompt the user for security credentials.
var html = HtmlService.createHtmlOutputFromFile('authorization_dialog');
SpreadsheetApp.getUi()
.showModalDialog(html, 'Authorization Dialog');
The HTML file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
Authorization Code:
<input type="text" name="authorization_code"><br><br>
Account ID:
<input type="text" name="account_id"><br><br>
Enter account details...
<br>
<br><br>
<input type="button" value="OK"
onclick="google.script.run.withSuccessHandler(success_callback).getCredentials(this.parentNode)" />
<input type="button" value="Close"
onclick="google.script.host.close()" />
</form>
<script>
// Using this call back prevents the need to hit the Close Button after OK.
function success_callback() {
google.script.host.close(); // Close the dialog.
}
</script>
</body>
</html>
If you don't need a response from the server-side function, simply omit 'withSuccessHandler';
function func_client(){
google.script.run.func_server();
google.script.host.close();
}
In this case, the server-side code will continue executing without locking your client's UI - you can call any other functions inside 'func_server'.
If you'd like to process a response from the first function call, call the second function from 'success_callback'. The dialog will be closed without waiting for the google.script.run to complete, but the server code will continue executing.
In the example below, the 1st server function passes form data back to the client where 'success_callback' immediately invokes another server function that takes a while to complete (it logs each file in my Google Drive);
Client:
<form id="form">
.....
<input type="submit" id="ok" value="OK" />
<input type="button" value="Close" onclick="google.script.host.close()" />
.....
</form>
<script>
window.onload = function(){
document.getElementById("form")
.addEventListener("submit", function(e){
e.preventDefault();
google.script.run
.withSuccessHandler(success_callback)
.logFormData(this);
});
}
function success_callback(response) {
console.log(response);
google.script.run.scanFiles();
google.script.host.close(); // Close the dialog.
}
</script>
Server:
function showDialog(){
var ui = SpreadsheetApp.getUi();
//IMPORTANT: client-side scripts won't be executed
//without calling evaluate() on the HtmlTemplate object before passing it to UI;
var template = HtmlService.createTemplateFromFile("dialog");
var html = template.evaluate();
ui.showModalDialog(html, "dialog");
}
function logFormData(formData){
return formData;
}
function scanFiles() {
var files = DriveApp.getFiles();
var file;
while (files.hasNext()) {
file = files.next();
Logger.log(file.getName() + ": " + file.getMimeType());
}
}

Google apps script get user input with no length limit

I want to take user input (HTML specifically) using either:
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Paste HTML below');
or
var input = Browser.inputBox('Paste HTML below', Browser.Buttons.OK_CANCEL);
These work fine for small inputs, however when copying over the entire HTML for a page of interest an error occurs (in each case). This error cannot be caught, it simply crashes the script.
Do you know why this is happening? I can't find anything in the docs that mention limits on input size.
Any experience doing this a different way?
Edit: as per a suggestion in the comments, I have tried another method (below). This also fails (with no error message) when passed large input.
First I set up Page.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Paste Sitemap Content Below
<textarea id="user-input-box" rows="4" cols="50"></textarea>
<script>
function logToConsole() {
var userInput = document.getElementById("user-input-box").value;
google.script.run.doSomething(userInput);
}
</script>
<input type="button" value="Close" onclick="logToConsole();google.script.host.close();" />
</body>
</html>
Then in file Code.gs
function testDialog() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi()
.showModalDialog(html, 'My custom dialog');
}
function doSomething(userInput){
Logger.log(userInput);
}
I just ran into the same problem and couldn't log the error. In my case as is yours, you're calling your logToConsole() function and then directly after you're closing the dialog by using google.script.host.close();
google.script.host.close() is the problem. For some reason it can cancel the script execution - this typically happens when you're sending a lot of data back. The trick is to use a successHandler when you call your script which then calls google.script.host.close(). This way, the data transfer from the dialog finishes correctly and when you call withSuccessHandler(), that callback closes the dialog. Try this amendment to your code:
<script>
function logToConsole() {
var userInput = document.getElementById("user-input-box").value;
google.script.run.withSuccessHandler(closeDialog).doSomething(userInput);
}
function closeDialog() {
google.script.host.close();
}
</script>
<input type="button" value="Close" onclick="logToConsole()" />

Create a Google Form in Pop up of Google Spreadsheet. Could this be done?

Reference :
Single Google Form for multiple Sheets
Re-claim :
I have a little bit hard to made my writing some good or as well to
be understanding (less english).
I have a little insight about a Google Apps Script (GAS).
I have change "MyURLDoc" and "MyIdDoc" bellow as cosinderring of
mine.
Question :
How do I make a Google Form be inside of a Pop up what I've made in Google Spreadsheet ?
Attempt 1 :
function goToURL() {
FormApp.openByUrl(//*** MyURLDoc! ***//);
}
Attempt 2 :    
Following as the reference has worte there!
function goToForm() {
var form = FormApp.openById(//*** MyIdDoc! ***//),
    formUrl = form.getPublishedUrl(),
    response = UrlFetchApp.fetch(formUrl),
    formHtml = response.getContentText(),
    htmlApp = HtmlService
.createHtmlOutput(formHtml)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Ta Daaa!')
.setWidth(500)
.setHeight(450); SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
}
Problem :
It says always like this:     " No item with the given ID could be found or You do not have permission "
Creating a Sidebar with a Google Form
I just went to an old form I have and got the embed code. I loaded into a sidebar that I had on another project and pasted the embed code which is an iframe and it loaded perfectly except for the size and I ran the form and sure enough it loaded data into the spreadsheet that contains it.
I thought I'd go ahead and add a complete example. This is a simple example which creates a form for inputting time stamped text into a spreadsheet. It's done two ways. The first technique uses standard html, javascript, JQuery and Google Script. The second technique is accomplished by just creating a form and embedding it into a simple html page. Both versions fit into the side bar and both are linked to spreadsheet pages where the text is loaded and timestamped.
Code.gs:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('createTextEntryForm', 'createTextEntryForm')
.addToUi();
loadSideBar();
SpreadsheetApp.getUi().createMenu('My Menu').addItem('loadSidebar', 'loadSideBar').addToUi();
}
//This loads the text into the spreadsheet for the html version of the form.
function dispText(txt)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Notes');
var ts=Utilities.formatDate(new Date(), 'GMT-6', "M/dd/yyyy HH:mm:ss");
var row=[];
row.push(ts);
row.push(txt);
sht.appendRow(row);
return true;
}
function loadSideBar()
{
var userInterface=HtmlService.createHtmlOutputFromFile('formBar');//sidebar for html and formBar for form
SpreadsheetApp.getUi().showSidebar(userInterface);
}
//This is the form
function createTextEntryForm()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var form=FormApp.create('Form On A Sidebar');
form.setDescription('Enter Your Message and Push Submit when complete.')
.setConfirmationMessage('Message Saved and TimeStamped.')
.setAllowResponseEdits(true)
.setAcceptingResponses(false)
.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
var containerLink=form.addParagraphTextItem();
containerLink.setTitle('Enter your comment now.')
.isRequired();
}
sidebar.html which is the html version of the form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function sendText()
{
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(clearText)
.dispText(txt);
}
function clearText()
{
$('#txt1').val('');
}
console.log("My code");
</script>
</head>
<body>
<textarea id="txt1" rows="12" cols="35"></textarea>
<br />
<input id="btn1" type="button" value="submit" onClick="sendText();" />
</body>
</html>
formBar.html is where the form is embedded:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<iframe src="FormURL?embedded=true#start=embed" width="300" height="550" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>
</body>
</html>
This is what the spreadsheet and sidebars look like:

Close dialog when both dialog and custom sidebar are present

I'm having trouble with the google.script.host.close() command in that it is closing my sidebar rather than the dialog.
function clickWeek() {
setWeekColor('week', '#7FFF00');
setMonthColor('month', '#d6d6c2');
setPressColor('press', '#d6d6c2');
setAllDataColor('allData', '#d6d6c2');
google.script.run.withSuccessHandler(google.script.host.close).weekAheadCreate();
}
The dialog is opened from the top of the weekAheadCreate() fucntion as per below:
var htmlOutput = HtmlService
.createHtmlOutput('<p>Please wait a moment...</p>')
.setWidth(250)
.setHeight(80);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Loading');
Any ideas how I can force the google.script.host.close() to act on the dialog rather than the sidebar?
The close() method closes the current dialog/sidebar, and asuming the clickWeek() is in your sidebar, it will close it instead of the dialog. You need to run the close() method inside the dialog.
How about you fire your server-side function when the dialog is created and when the withSuccessHandler() detects a successful return then it closes the dialog using close().
You will need to use createHtmlOutputFromFile when creating the dialog insted of createHtmlOutput and inside your html use the <script> tag. Here's an example:
code.gs
function createDialog(){
var htmlOutput = HtmlService
.createHtmlOutputFromFile('dialog')
.setWidth(250)
.setHeight(80);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Loading');
}
function doBusyStuff(){
// Busy stuff
}
dialog.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
(function() {
// Runs the busy stuff and closes the dialog using .close() on success
google.script.run
.withSuccessHandler(google.script.host.close)
.doBusyStuff();
})();
</script>
</head>
<body>
<p>Please wait a moment...</p>
</body>
</html>