Альтернативы SuggestBox в Google UiApp

Я пытаюсь создать относительно простое приложение (по крайней мере, так казалось две недели назад) для каталогизации периодического потребления в библиотеке. Мне нужна форма с двумя полями: ввод текста для заголовков периодических изданий и ввод даты для даты публикации. Затем мне нужна эта форма для отправки в электронную таблицу Google. Я мог бы просто использовать общую форму, но она нужна мне для автозаполнения названия периодического издания по мере ввода информации.
Я использую Google Apps, электронные таблицы и сайты Google, потому что они бесплатны и делают почти все, что мне нужно. . Вот камень преткновения. Я могу создать HTMLService, который отлично автозаполняется из листа Google. Я в основном точно следовал этому сообщению.
Я могу создать сценарий UiApp для отправки на лист. Я просто не могу сделать и то, и другое в одном проекте. Код следующий:

function doGet() {
  var doc = SpreadsheetApp.openById(SPREADSHEET_ID);
  var app = UiApp.createApplication().setTitle('Periodical Intake');
  // Create a grid with 3 text boxes and corresponding labels
  var grid = app.createGrid(3, 2);
  grid.setWidget(0, 0, app.createLabel('Title:'));

  // Text entered in the text box is passed in to pTitle
  // The setName method will make those widgets available by
  // the given name to the server handlers later
  grid.setWidget(0, 1, app.createTextBox().setName('pTitle').setId('pTitle'));
  grid.setWidget(1, 0, app.createLabel('Date:'));
  grid.setWidget(1, 1, app.createDateBox().setName('date').setId('date'));


  // Text entered in the text box is passed in to city.

  // Create a vertical panel..
  var panel = app.createVerticalPanel();

  // ...and add the grid to the panel
  panel.add(grid);

 // Here's where this script diverges from the previous script.
  // We create a horizontal panel called buttonPanel to hold two buttons, one for submitting the contents of the form
  // to the Spreadsheet, the other to close the form.

  var buttonPanel = app.createHorizontalPanel();

  // Two buttons get added to buttonPanel: button (for submits) and closeButton (for closing the form)
  // For the submit button we create a server click handler submitHandler and pass submitHandler to the button as a click handler.
  // the function submit gets called when the submit button is clicked.
  var button = app.createButton('submit');
  var submitHandler = app.createServerClickHandler('submit');
  submitHandler.addCallbackElement(grid);
  button.addClickHandler(submitHandler);
  buttonPanel.add(button);

  // For the close button, we create a server click handler closeHandler and pass closeHandler to the close button as a click handler.
  // The function close is called when the close button is clicked.
  var closeButton = app.createButton('close');
  var closeHandler = app.createServerClickHandler('close');
  closeButton.addClickHandler(closeHandler);
  buttonPanel.add(closeButton);


  // Create label called statusLabel and make it invisible; add buttonPanel and statusLabel to the main display panel.
  var statusLabel = app.createLabel().setId('status').setVisible(false);
  panel.add(statusLabel);

  panel.add(buttonPanel);

  app.add(panel);
  return app;
}

// Close everything return when the close button is clicked
function close() {
  var app = UiApp.getActiveApplication();
  app.close();
  // The following line is REQUIRED for the widget to actually close.
  return app;
}

// function called when submit button is clicked
function submit(e) {

  // Write the data in the text boxes back to the Spreadsheet
  var doc = SpreadsheetApp.openById(SPREADSHEET_ID);
  var lastRow = doc.getLastRow();

  var cell = doc.getRange('a1').offset(lastRow, 0);
  cell.offset(0, 1).setValue(e.parameter.pTitle);
  cell.offset(1, 2).setValue(e.parameter.date);


  // Clear the values from the text boxes so that new values can be entered
  var app = UiApp.getActiveApplication();
  app.getElementById('pTitle').setValue('');
  app.getElementById('date').setValue('');
  // Make the status line visible and tell the user the possible actions
  app.getElementById('status').setVisible(true).setText('The periodical ' + e.parameter.pTitle + ' was entered.' +
  'To add another, type in the information and click submit. To exit, click close.');
  return app;
}​

Я мог бы использовать свою функцию getAvailableTags, если можно использовать jQuery в UiApp (я так не думаю). Другое предложение — использовать submitBox, но кажется, что он устарел. Я в своем уме. Прошло две недели, и я чувствую, что ничего не добился. Кто-нибудь может помочь библиотекарю?


person Brendan Ryan    schedule 11.03.2014    source источник
comment
поскольку мы не можем смешивать UiApp и HTMLService, почему бы не создать свою форму в HTMLService, интегрировав автозаполнение в саму форму?   -  person Serge insas    schedule 12.03.2014


Ответы (1)


Вот пример формы, созданной с помощью HTMLService, которая хранит данные в электронной таблице. У меня также есть загрузка файла, которая вам не нужна, но я подумал, что это может заинтересовать кого-то еще... Функцию автозаполнения должно быть легко интегрировать, используя существующий код, заимствованный у Могсдада.

код.gs:

    function doGet() {
      return HtmlService.createHtmlOutputFromFile('index');
    }    

   function serverFunc(theForm) {
      var fileBlob = theForm.theFile;         // This is a Blob.
      var name = theForm.name;
      var number = theForm.number;
      var adoc = DocsList.createFile(fileBlob);   
      var sh = SpreadsheetApp.openById('1dx0mr4Dy64jqmliTjFyHF7rZW4TZ_PPkWyA_H3WTRcA').getSheetByName('Sheet1');
      sh.getRange(sh.getLastRow()+1,1,1,4).setValues([[adoc.getName(),adoc.getUrl(),name,number]]);
       return adoc.getUrl();
    }

index.html :

<style>
p {
margin:40px;
font-family:arial,sans-serif;
font-size:10pt;
color:#AAA
}
</style>
<p>
Test this file upload form :
<br><br>
<form>
   Enter you name    <input type="text" name="name" ><br>
   Enter your number <input type="text" name="number"><br>
   select your file  <input type="file" name="theFile"><br>
   <input type="button"  value="UpLoad" id="button" onclick="google.script.run.withSuccessHandler(cliHandler).serverFunc(this.parentNode)">
</form>
</div><br>
<div id="url" >
</div><br>
<div id="urlText" >
</p>

<script>

function cliHandler(e){
   document.getElementById('button').value = "Your file has been uploaded" ; 
   var divUrl = document.getElementById('url');
   divUrl.innerHTML = '<a href="' + e + '">Open the file</a>';
   document.getElementById('urlText').innerHTML = "url : "+e;
   }

</script> 

РЕДАКТИРОВАТЬ: Вот версия, основанная на вашем коде с рабочей формой и автозаполнением:

код.gs

function doGet() {
  return HtmlService.createTemplateFromFile('Autocomplete').evaluate().setTitle('Periodical Intake');
}


function getAvailableTags() {

  var ss = SpreadsheetApp.openById("0Agz7u97dbdECdGh6QVcyb2NVeFByTnlYeU5KcDdSRWc");
  var s = ss.getSheetByName("Cataloging Key");
  var data = s.getDataRange().getValues();
  var headers = 0; // number of header rows to skip at top
  var tagColumn = 0; // column # (0-based) containing tag

  var availableTags = [];
  for (var row=headers; row < data.length; row++) {
    availableTags.push(data[row][tagColumn]);
  }

  return( availableTags );
}


function doPost(e) {
  var title = e.title;
  var date = e.date;
  Logger.log(title+'  '+date);
}

Автозаполнение.html

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
p {
margin:40px;
font-family:arial,sans-serif;
font-size:10pt;
color:#AAA
}
</style>
<p>
Test this file upload form :
<br><br>
<div>
<form class="ui-widget" >
      <input id="title" type=text placeholder="Periodical Title:" name="title" /><br />
      <input id="date"  type=date placeholder="Publication Date: " name="date" /><br>
      <input type="button" value="Submit"
      onclick="google.script.run.doPost(this.parentNode)" />
</form>

</div><br>
<div id="url" >
</div><br>
<div id="urlText" >
</p>

<script>
// This code in this function runs when the page is loaded.

$(function() {
  google.script.run.withSuccessHandler(buildTagList).getAvailableTags();
});

function buildTagList(availableTags) {
  $( "#title" ).autocomplete({
    source: availableTags
  });
}

</script>
person Serge insas    schedule 12.03.2014
comment
Спасибо за помощь. Извините, но я интегрировал это в свою функцию автозаполнения от Mogsdad. Автозаполнение все еще работает, но форма не отправляется. Нужно ли мне изменить какой-либо из serverFunc, чтобы указать имя формы? Ссылка на код @Serge - person Brendan Ryan; 12.03.2014
comment
Спасибо еще раз. Это заводит меня дальше, но как мне определить электронную таблицу Google, в которую я хочу отправить данные формы? Я также хочу, чтобы форма сбрасывалась при отправке. @Серж - person Brendan Ryan; 12.03.2014
comment
использовать часть функции serverFunc(theForm) из первой версии в функции doPost в code.gs. чтобы перепродать форму, вам нужно будет сделать это в клиентском javascript. Сейчас нет времени, но я попробую обновить эти функции позже снова;) - person Serge insas; 12.03.2014
comment
Еще раз большое спасибо. Я очень ценю это, хотя мне нужно немного больше помощи. Я играл с этим, но не могу правильно интегрировать serverFunc в doPost, чтобы разрешить публикацию. @Серж - person Brendan Ryan; 13.03.2014