【问题标题】:Get variable value from different function in Google Apps Script从 Google Apps 脚本中的不同函数获取变量值
【发布时间】:2021-07-12 14:40:46
【问题描述】:

对不起,我是个菜鸟,

我用谷歌应用程序脚本制作了一个表单,包括一个上传文件的上传按钮。上传文件后,我想获取该文件的超链接并在不同的函数中使用它,在其中我获取用户输入的值并将它们放入谷歌表中。

这是代码.gs: 上传后将 obj 保存到驱动器:

function saveFile(obj) {
  var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName);
  var file = DriveApp.getFolderById(globalVariables().driveFolder).createFile(blob);
  cellFormula = 'hyperlink("' + file.getUrl() + '";"' + file.getName() + '")';
}

我正在尝试将 cellFormula 值转换为不同的函数:

function getFormValues(formObject){
  if(formObject.RecId && checkID(formObject.RecId)){    
    var values = [[
                  formObject.RecId.toString(),
                  formObject.datum,
                  [...],
                  cellFormula
                  ]];
    
  } else{
    var values = [[
                  new Date().getTime().toString(),//https://webapps.stackexchange.com/a/51012/244121
                  formObject.datum,
                  [...],
                  cellFormula
                  ]];
  }
  return values;
}

但这当然行不通。如何将 cellFormula 从第一个函数获取到另一个函数?

提前谢谢你!

编辑:完整代码(仅相关位): 表单.html:

<form id="myForm" class="p-2 border border-light rounded bg-light" onsubmit="handleFormSubmit(this)">
[ ... bunch of input fields ... ]
  
    <button type="submit" id="submit" class="btn btn-primary">Doorvoeren</button>
      
</form>


<form id="myFormUpload" class="p-2 border border-light rounded bg-light">
         <input type="file" name="upload" id="files"/> 
         <input type='button' id="uploadButton" value='Upload' onclick='getFiles()'> 
         <br>    <div id="progress">  </div>
</form>

JavaScript.html:

  function handleFormSubmit(formObject) {
    google.script.run.withSuccessHandler(createTable).processForm(formObject);
    document.getElementById("myForm").reset();
    hidenForm();
    
    // DATUM INVULLEN IN DATUM VELD
    var field = document.querySelector('#datum');
    var date = new Date();
    // Set the date
    field.value = date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString().padStart(2, 0) +  '-' + date.getDate().toString().padStart(2, 0);
  }



  function getFiles() {
      document.getElementById("uploadButton").disabled = true;
      const progressText = document.getElementById("progress");
      const f = document.getElementById('files');
      var uploadCompletedCount = 0;
      progressText.innerHTML = "Uploading file " + (uploadCompletedCount + 1) + "/" + [...f.files].length + "";
      [...f.files].forEach((file, i) => {
        const fr = new FileReader();
        fr.onload = (e) => {
          const data = e.target.result.split(",");
          const obj = {fileName: f.files[i].name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]};
          google.script.run.withSuccessHandler((id) => {
            uploadCompletedCount++;
            progressText.innerHTML = "Upload voltooid";
            if (uploadCompletedCount >= [...f.files].length){
              google.script.host.close();
            }
            else{
              progressText.innerHTML = "Bestand uploaden... " + (uploadCompletedCount + 1) + "/" + [...f.files].length + "";
            }
          }).saveFile(obj);
        }
        fr.readAsDataURL(file);
        //var fotourl = fr.readAsDataURL(file);
        //return fotourl;
      });
    }



还有 Code.gs:

/* 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 getUrenGebruiker(); 
}



function getFormValues(formObject){
  if(formObject.RecId && checkID(formObject.RecId)){    
    var values = [[
                  formObject.RecId.toString(),
                  formObject.datum,
                  [ ... more fields ...] 
                  cellFormula
                  ]];
    
  } else{
    var values = [[
                  new Date().getTime().toString(),//https://webapps.stackexchange.com/a/51012/244121
                  formObject.datum,
                  [ ... more fields ...] 
                  cellFormula
                  ]];
  }
  return values;
}



function saveFile(obj) {
  var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName);
  var file = DriveApp.getFolderById(globalVariables().driveFolder).createFile(blob);
  cellFormula = 'hyperlink("' + file.getUrl() + '";"' + file.getName() + '")';
}

所以在提交表单时,它会从输入字段中获取所有数据。上传是我放在另一个表单中的不同表单。当点击上传按钮时,它会激活函数 getFiles()。

【问题讨论】:

  • 你能分享一个完整的代码吗?您是否使用表单提交触发器?提交表格时。我需要知道你什么时候打电话给saveFile(),什么时候打电话给getFormValues()。你的formObjectobj的内容是一样的吗?
  • saveFile() 本质上来自不同的形式。也许我必须以不同的方式设计它,但如果可能的话,我想这样做。编辑:我将编辑原始帖子以包含完整代码。
  • 感谢您提供更多信息。我几乎了解您的代码的要点。但我没看到你打算打电话给getFormValues()
  • 因为我不知道您如何称呼getFormValues()(不确定它是在您的javascript html 中还是在应用程序脚本中)。您可能希望在 saveFile() 中返回 cellFormula,然后将其保存在 javascript html 的全局变量中(假设您计划在 html 代码中调用 getFormValues())
  • 很抱歉。我将它包含在第 1 篇文章的代码中。就是这一点,在 Code.gs 中:function processForm(formObject){ if(formObject.RecId &amp;&amp; checkID(formObject.RecId)){ 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 getUrenGebruiker(); }

标签: google-apps-script


【解决方案1】:

这是一个选项,您可以使用Properties Service 将单元格公式字符串保存在应用脚本中。

示例代码:

function saveFile(obj) {
  var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName);
  var file = DriveApp.getFolderById(globalVariables().driveFolder).createFile(blob);
  cellFormula = 'hyperlink("' + file.getUrl() + '";"' + file.getName() + '")';

  var scriptProp = PropertiesService.getScriptProperties();
  var formulaStr = scriptProp.getProperty('formula');
  Logger.log(formulaStr);
  if(formulaStr){
    formulaStr = formulaStr +','+cellFormula;
    Logger.log(formulaStr);
    scriptProp.setProperty('formula',formulaStr);
  }
  else{
    //save initial data to script properties
    scriptProp.setProperty('formula',cellFormula);
    Logger.log("Saved")
  }
}

function getFormValues(formObject){
  //get saved formula
  var scriptProp = PropertiesService.getScriptProperties();
  var formulaStr = scriptProp.getProperty('formula');
  var cellFormula = [];

  Logger.log(formulaStr);
  Logger.log(cellFormula);
  if(formulaStr){
    cellFormula = formulaStr.split(',');
  }
  Logger.log(cellFormula);
  //Reset script property
  scriptProp.deleteProperty('formula');

  //Do your original processing here
}

注意:

  • 我注意到在您的代码中可能会在您的表单中上传多个文件。因此,此示例代码可以处理/保存表单中上传的每个文件的多个 cellFormula
  • 我的解决方案是假设您先上传文件,然后再单击表单的提交按钮。
  • 您可以删除我用于调试的日志。

它有什么作用?

  1. 当您使用上传按钮上传文件时,每个文件都有自己的cellFormula。在saveFile() 中,使用属性键formula 获取脚本属性。如果尚不存在,请创建属性键并根据cellFormula 字符串设置其值。如果密钥已经存在,则将当前的cellFormula 字符串附加到comma
  2. 提交表单时,使用属性键formula 获取脚本属性。如果存在,则使用string.split() 拆分公式字符串以获得cellFormula 字符串的数组。然后根据您的偏好处理每个保存的公式
  3. 请记住,一旦您处理了您在提交表单时保存在脚本属性中的公式,您需要删除现有密钥以清除脚本属性,以便下次通过文件上传提交表单。

【讨论】:

  • 如果您对建议的解决方案有任何问题,请告诉我,以便我进行相应更新。
  • 天哪!我很感激!非常感谢您的时间和精力!它终于奏效了!我稍微修改了一下,因为它给出了列表错误:GoogleJsonResponseException: API call to sheet.spreadsheets.values.append failed with error: Invalid values[16][20]: list_value { values { string_value: "hyperlink(\" drive.google.com/file/d/1Lexc61H0ODkjyDCJtPPo-cu6kxkFXJbJ/…\";\"IMG_8004.JPG\")" } } at appendData(Code:179:44) at processForm(Code:58:5) 但它有效。再次感谢。 :)
  • 很高兴听到这个消息。顺便说一句,如果我们回答了您的问题,请点击接受按钮。通过这样做,社区中可能与您有同样担忧的其他人将知道他们的问题可以得到解决。如果您无法使用接受按钮,请随时告诉我。 How to accept answer
猜你喜欢
  • 2023-01-07
  • 1970-01-01
  • 2022-10-18
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多