// Archivo Código.gs
// URL que genera Google Sheet al solicitar link para compartir
var myGoogleSheetURL =
"OCULTO";
// Nombre de la hoja donde estan nuestros datos
var myGoogleSheetName = "OCULTO";
/**
* Función de inicialización ( la primera que se ejecuta )
*/
function doGet() {
// Muestra el HTML
var template = HtmlService.createTemplateFromFile('formulario');
return template.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/**
* Funcion que sera llamada al hacer click en el boton del formulario
* @param form formulario recibido desde el frontend
*/
function receiveForm(form) {
// Obtenemos el valor del campo userId
var userId = form.userId;
// Llama a la funcion para buscar datos, pasandole el parametro
return searchData(userId);
}
/**
* Busca en la hoja de calculos los datos del usuario
* @param userId ID del usuario que queremos buscar
*/
function searchData(userId) {
// Obtiene la hoja de calculos
var sheet = getSpreadSheet(myGoogleSheetURL, myGoogleSheetName);
// Recorre todas las filas buscando la coincidencia del userID con el valor
// de la columna 0
var rowsResult = sheet
.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn())
.getValues()
.filter(function (row) {
return row[0] === userId.matches(userId);
});
// Obtiene el resultado
var firstRow = rowsResult[0];
// Parsea cada uno de los campos
var user = {
id: firstRow[0],
email: firstRow[1],
phone: firstRow[2],
};
// Serializa el OBJ para enviar la respuesta al frontend
var result = JSON.stringify(user);
return result;
}
/**
* Obtiene una hoja de calculo según la URL y nombre de la hoja especificados
*/
function getSpreadSheet(url, sheetName) {
var ss = SpreadsheetApp.openByUrl(url);
var sheet = ss.getSheetByName(sheetName);
return sheet;
}
FORMULARIO.HTML:
<!-- archivo formulario.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>OCULTO</title>
<link rel="icon" href="OCULTO">
<base target="_top" />
<style>
:root {
--primary-color: #4caf50;
}
body {
text-align: center;
font-family: 'Helvetica', 'Arial', sans-serif;
}
input {
font-size: 16px;
}
input[type="text"] {
border: none;
border-bottom: 2px solid var(--primary-color);
margin: 10px;
padding: 10px;
text-align: center;
}
input[type="button"] {
background-color: var(--primary-color);
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 10px 2px;
cursor: pointer;
}
input[type="button"]:disabled {
background-color: #dadada;
}
</style>
<title>OCULTO</title>
</head>
<body>
<!-- Inicio del formulario-->
<form action="#">
<input
id="inputUserId"
type="text"
value=""
name="userId"
placeholder="PRODUCT NAME"
onfocus="clearDiv()"
onkeyup="javascript:this.value=this.value.toUpperCase();"
/>
<br />
<input
id="btnSend"
type="button"
onClick="formSubmit()"
value="Search"
/>
</form>
<!-- Fin del formulario-->
<!-- div donde se mostraran los resultados -->
<br>
<div id="divResponse"></div>
</body>
<script type="text/javascript">
// Función que se ejecuta al presionar el boton del formulario
function formSubmit() {
document.getElementById("divResponse").innerHTML = "Searching...";
// Llama a la funcion receiveForm de nuestro script
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(onFailure)
.receiveForm(document.forms[0]);
// Deshabilita los inputs y el btn mientra se hace la llamada
disableInputs();
}
// Función que se ejecuta cuando la busqueda ocurre con exito
function onSuccess(response) {
// Parsea la respuesta
var user = JSON.parse(response);
// Carga el campo email de la respuesta en el div
document.getElementById("divResponse").innerHTML = user.email;
// Habilita el campo y boton
enableInputs();
}
// Función que se ejecuta cuando la busqueda ocurre con ERROR
function onFailure() {
// Pone mensaje en div
document.getElementById("divResponse").innerHTML = "Fabric not found";
enableInputs();
}
// Desabilita boton y campo de texto
function disableInputs() {
document.getElementById("btnSend").disabled = true;
document.getElementById("inputUserId").disabled = true;
}
// Habilita boton y campo de texto
function enableInputs() {
document.getElementById("btnSend").disabled = false;
document.getElementById("inputUserId").disabled = false;
}
function clearDiv() {
document.getElementById("divResponse").innerHTML = "";
}
</script>
</html>
Muchas gracias de antemano