Call to database from Javascript in aspx page - javascript

I have a gridview using devexpress tools that is populated on page load. When I select a row I have button that will allow me to edit the information in that row by popping up an edit box that allows me to change the information. The issue I am having is when they click that button the data that was behind the gridivew could have changed so I want to be able to query the database again (using some parameters from the selected row) when that edit button is clicked.
Here is the query that is ran when the 'edit' button is clicked.
function ShowPopupEditInventory() {
$.when(getFocusedInventory()).then(function (x) {
popupControlEditInventory.Show();
});
function getFocusedInventory(s, e) {
grid.GetRowValues(grid.GetFocusedRowIndex(), 'StorageLocation;LP;Sku_Alpha;LotCode;ExpirationDate;FIFOReferenceDate;ManufactureDate;InventoryStatus;SellableUnitQuantity;ReceiveDate;InventoryDetailID;Area', getFocusedInventoryValues);
}
function getFocusedInventoryValues(values) {
var fStorageLocation = values[0];
var fLP = values[1];
var fSku_Alpha = values[2];
var fLotCode = values[3];
var fExpirationDate = values[4];
var fFIFOReferenceDate = values[5];
var fManufactureDate = values[6];
var fInventoryStatus = values[7];
var fSellableUnitQuantity = values[8];
var fReceiveDate = values[9];
var fInventoryDetailID = values[10];
var fArea = values[11];
editInventoryStorageLocation.SetText(fStorageLocation);
editInventoryLP.SetText(fLP);
editInventoryItem.SetText(fSku_Alpha);
editInventoryQty_OldValue.SetText(fSellableUnitQuantity);
editInventorySts_OldValue.SetText(fInventoryStatus);
editInventoryLot_OldValue.SetText(fLotCode);
txtEditInventoryLot.SetText(fLotCode);
$(".editInventoryLot").val(fLotCode);
editInventoryStatus.SetValue(fInventoryStatus)
editInventoryUnitQuantity.SetText(fSellableUnitQuantity);
editInventoryDTL_No.SetText(fInventoryDetailID);
editInventoryNotes.SetText('');
$(".editInventoryAdjustmentCode").prop("selectedIndex", 0);
editInventoryArea.SetText(fArea);
editInventoryLot.Focus();
btnOKEditInventory.SetEnabled(true);
}
}

Related

How do I add a new value to a Google Sheet from a text field in a Web App and then automatically update the associated dropdown?

WARNING: I'm not a programmer by trade.
Ok. Got the disclaimer out of the way. So this might not be the best way to do this but here is the scenario. I have a dropdown that gets populated via a Google Sheet. The user chooses a selection from the list but this dropdown does not have all of the possible values it could have. There will likely be a time when the user needs a new value added. While I could manually update the spreadsheet as new values are requested that introduces an element of human availability to get this done and I'm not always available.
What I would prefer is a self-serve model. I want to supply the user with a text field where they can enter the new value and submit it to the Google Sheet. Then I would like the dropdown to be updated with the new value for the user to choose.
Now, I realize that I could just submit the value in the new field to the Google Sheet but that will require building a condition to see whether it is the dropdown or text field that has a value in it. I'd also need some type of error handling in case both the dropdown and text field have values. That seems like a bigger headache to program then my ask.
I'm not sure what code you would need to see to help make this work but here is what I think might help.
doGet function
function doGet(e){
var ss = SpreadsheetApp.openById(ssId)
var ws = ss.getSheetByName("External");
var range = ws.getRange("A2:D2");
var valuesArray = [];
for (var i = 1; i <= range.getLastColumn(); i++){
var lastRowInColumn = range.getCell(1, i).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var list = ws.getRange(2,i,lastRowInColumn-1,1).getValues();
valuesArray.push(list);
}
var userEmail = Session.getActiveUser().getEmail();
var sourceListArray = valuesArray[2].map(function(r){ return '<option>' + r[0] + '</option>'; }).join('');
var productListArray = valuesArray[3].map(function(r){ return '<option>' + r[0] + '</option>'; }).join('');
var tmp = HtmlService.createTemplateFromFile("config");
tmp.productList = productListArray;
return tmp.evaluate();
}
Add to Google Sheet
function userClicked(tagInfo){
var ss = SpreadsheetApp.openById(ssId)
var ws = ss.getSheetByName("Data");
ws.appendRow([tagInfo.email, tagInfo.source, tagInfo.product, new Date()]);
}
Add record
function addRecord(){
var tagInfo = {};
tagInfo.product = document.getElementById("product").value;
google.script.run.userClicked(tagInfo);
var myApp = document.getElementById("source");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
var myApp = document.getElementById("brand");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
var myApp = document.getElementById("product");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
}
How dropdowns are populated in the HTML.
<div class="input-field col s3">
<select id="product" onchange="buildURL()">
<option disabled selected value="">Choose a product</option>
<?!= productList; ?>
</select>
<label>Product</label>
</div>
Need to see anything else? I think it might be relatively easy to add the new value to the column but the tricky part seems to be the update of only that one dropdown and not the entire app. To me it seems like I want to trigger the doGet() function again but only for that specific dropdown. Thoughts?
UPDATE: current code to add new value to dropdown
function addProduct() {
let newProd = document.getElementById("newProduct").value;
google.script.run.withSuccessHandler(updateProductDropdown).addNewProduct(newProd);
document.getElementById("newProduct").value = "";
}
function updateProductDropdown(newProd){
var newOption = document.createElement('option');
newOption.value = newProd;
newOption.text = newProd;
document.getElementById('product').add(newOption);
}
UPDATE2: App Scripts function to add new value to column in spreadsheet
function addNewProduct(newProd){
var columnLetterToGet, columnNumberToGet, direction, lastRow, lastRowInThisColWithData, rng, rowToSet, startOfSearch, valuesToSet;
var ss = SpreadsheetApp.openById(ssId);
var ws = ss.getSheetByName("List Source - External");
lastRow = ws.getLastRow();
//Logger.log('lastRow: ' + lastRow)
columnNumberToGet = 9;//Edit this and enter the column number
columnLetterToGet = "I";//Edit this and enter the column letter to get
startOfSearch = columnLetterToGet + (lastRow).toString();//Edit and replace with column letter to get
//Logger.log('startOfSearch: ' + startOfSearch)
rng = ws.getRange(startOfSearch);
direction = rng.getNextDataCell(SpreadsheetApp.Direction.UP);//This starts
//the search at the bottom of the sheet and goes up until it finds the
//first cell with a value in it
//Logger.log('Last Cell: ' + direction.getA1Notation())
lastRowInThisColWithData = direction.getRow();
//Logger.log('lastRowInThisColWithData: ' + lastRowInThisColWithData)
rowToSet = lastRowInThisColWithData + 1;
valuesToSet = [newProd];
ws.getRange(rowToSet, 9).setValues([valuesToSet]);
return newProd;
}
SOLUTION to Update Materialize Dropdown
function updateProductDropdown(newProd){
newProdOption = document.getElementById('product');
newProdOption.innerHTML += '<option>' + newProd + '</option>';
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
}
You can specify a client side callback function if you use google.script.run withSuccessHandler(callback) where your callback could update the list only and not the whole site.
Example:
google.script.run.withSuccessHandler(updateDropdownWidget).updateDropdownList(text_from_input)
Where updateDrownList(text_from_input) is a function in your Apps Script that adds text to the sheet using SpreadsheetApp for example, and returns the "text" to the callback function: updateDropdownWidget(text) which adds a new list item to the HTML drop-down list in your front end.
index.html:
<form>
<label for="newOption">New option for the dropdown:</label>
<input type="text" id="nopt" name="newOption">
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(updateDropdownWidget)
.updateDropdownList(document.getElementById('nopt').value)">
</form>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<?!= values; ?>
</select>
<script>
function updateDropdownWidget(text){
var option = document.createElement('option');
option.value = text;
option.text = text;
document.getElementById('cars').add(option);
}
</script>
Code.gs:
function doGet(e){
var ss = SpreadsheetApp.getActiveSheet();
var lastRow = ss.getDataRange().getLastRow();
var values = ss.getRange(1,1,lastRow,1).getValues();
var valuesArray = [];
for (var i = 0; i < values.length; i++){
valuesArray.push('<option value="'+values[i]+'">' +values[i]+ '</option>');
}
var tmp = HtmlService.createTemplateFromFile("index");
tmp.values = valuesArray;
return tmp.evaluate();
}
function updateDropdownList(text_from_input){
// Log the user input to the console
console.log(text_from_input);
// Write it to the sheet below the rest of the options
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getDataRange().getLastRow();
sheet.getRange(lastRow+1,1).setValue(text_from_input);
// Return the value to the callback
return text_from_input;
}
Here's an example:
In my Stack Over Flow spreadsheet I four buttons which can be used to run any function in 3 script files and every time I load the sidebar it reads the functions in those script files and returns them to each of the select boxes next to each button so that I test functions that I write for SO with a single click and I can select any function for any button. Here's the Javascript:
$(function(){//JQuery readystate function
google.script.run
.withSuccessHandler(function(vA){
let idA=["func1","func2","func3","func4"];
idA.forEach(function(id){
updateSelect(vA,id);
});
})
.getProjectFunctionNames();
})
Here is GS:
function getProjectFunctionNames() {
const vfilesA=["ag1","ag2","ag3"];
const scriptId="script id";
const url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content?fields=files(functionSet%2Cname)";
const options = {"method":"get","headers": {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
const res = UrlFetchApp.fetch(url, options);
let html=res.getContentText();
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), "Project Functions");
let data=JSON.parse(res.getContentText());
let funcList=[];
let files=data.files;
files.forEach(function(Obj){
if(vfilesA.indexOf(Obj.name)!=-1) {
if(Obj.functionSet.values) {
Obj.functionSet.values.forEach(function(fObj){
funcList.push(fObj.name);
});
}
}
});
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(funcList.join(', ')), "Project Functions");
return funcList;//returns to withSuccessHandler
}
Image:
Animation:

Passing appended text box values back to Google App Script Side

I have figured out how to append text boxes and set class as autocomplete therefore setting default values as the dynamic list generated in an avaliableTag function on the google app script side. I need to get each appended text box value back to the google app script side so the end user can submit the data and a new row of data will be appended to the google sheet. Here is my html code
<label for="units" style="font-size:125%;"><b>Number of items on Ticket</b></label>
<input type="text" name="units" id="units">
<!-- specified units by user-->
<button id = 'numitems' onclick = "getUnits()">Add items </button>
<!-- button that runs function to append appropriate # of boxes -->
</div>
<button id = 'submit' type = 'submit'name = "action">Submit </button>
Here is my google script code (left out doGet and HTML Service) these functions are what the user will submit to google sheet and the function that generates autocomplete options. Still need to get userInfo.MEDS
function userClicked(userInfo){
var ss = SpreadsheetApp.openByUrl('someURL');
var ws= ss.getSheetByName('Sheet1')
var user = Session.getActiveUser();
var timestamp = Utilities.formatDate(new Date(), 'CST', 'MM/dd/yyyy HH:mm:ss')
Logger.log(userInfo)
ws.appendRow([user,userInfo.id,userInfo.ticket,userInfo.items,userInfo.MEDS,timestamp]);
}
function getAvailableTags() {
var ss = SpreadsheetApp.openById("someId");
var s = ss.getSheetByName("someSheet");
var data= s.getRange("A2:A").getValues();
var headers = 1;
var tagColumn = 0;
var availableTags = [];
for (var row=headers; row < data.length; row++) {
availableTags.push(data[row][tagColumn]);
}
return( availableTags );
}
and finally here is the js/jquery side
var x=1
function appendRow()
{
var d = document.getElementById('left-col');
d.innerHTML += "<input type='text'class = 'autocomplete' id='tst"+ x++ +"'><br >";
}
function getUnits() {
var units = $("#units").val();
x=1
for (var count = 1; count < units; count++) {
$("<input type='text'class = 'autocomplete' id='tst"+ x++ +"'><br >").appendTo("#left-col");
}
var mednum = 0
$("#left-col").append("<input type='text'class = 'autocomplete' id='tst"+ x++ +"'>")
;
}
$(function() {
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
});
function buildTagList(availableTags) {
$( ".autocomplete" ).autocomplete({
source: availableTags
});
}
$('#submit').on('click', function (){
$('.autocomplete').each(function() {
var med = $(this).val();
console.log(med);
});
});
window.onload=function(){
document.getElementById('submit').addEventListener('click',buttonClick);
function buttonClick() {
var userInfo = {};
userInfo.Id = document.getElementById('ptid').value
userInfo.ticket = document.getElementById('ticket').value
userInfo.items = document.getElementById('items').value
}}
I need something that will take value of each appended box and let me store it in the userInfo object so it can be passed back to the gs side
You can use google.script.run to run a function in code.gs side and send the form object [1]. Also, you should prevent the default behavior for when the form is submitted:
function buttonClick() {
var userInfo = {};
userInfo.Id = document.getElementById('ptid').value
userInfo.ticket = document.getElementById('ticket').value
userInfo.items = document.getElementById('items').value
google.script.run.userClicked(userInfo)
}
$("#formID").submit(function(e){
e.preventDefault();
});
[1] https://developers.google.com/apps-script/guides/html/communication#forms

Using JavaScript in Google Scripts to transfer information to spreadsheet, but spreadsheet shows undefined

I am using Google Scripts UiApp in order to gather availability information. I want to send this information to a spreadsheet. I have used the example here: http://www.googleappsscript.org/advanced-examples/insert-data-in-sheet-using-ui-forms
to get me started in the right direction.
The Web App looks good and when clicking submit, the appropriate message displays. However, the values that are transferred to the spreadsheet say "undefined" for all of the entries.
How can I convince it to link the textbox entered data to the variables so that I can transfer to the spreadsheet?
Thanks!!
Here is some code:
var submissioSSKey = // Key removed
function doGet() {
var rows = 15
var columns = 15
var mygrid = UiApp.createApplication().setTitle("MLC Walk Ins Scheduling")
var panel = mygrid.createSimplePanel();
// Define the grid layout
var grid = mygrid.createGrid(rows, columns).setCellPadding(2).setCellSpacing(8)
// Create the text at the top
var Title = mygrid.createLabel("Walk-In Scheduling")
grid.setWidget(1, 1, Title)
(snip) - creating various checkboxes and textboxes
var text1 = mygrid.createTextBox().setName('name1')
grid.setWidget(3,9,text1)
var text6 = mygrid.createTextBox().setName('message1')
grid.setWidget(4,9,text6)
// Create the "submit" button
var submit_button = mygrid.createButton("Submit")
grid.setWidget(12,9,submit_button)
var infoLabel = mygrid.createLabel('Availability inserted successfully.').setVisible(false).setId('info');
grid.setWidget(13,9,infoLabel)
var handler = mygrid.createServerClickHandler('insertInSS');
handler.addCallbackElement(panel);
submit_button.addClickHandler(handler);
panel.add(grid);
mygrid.add(panel);
mygrid.add(grid);
return mygrid
}
Then the function call for the button:
//Function to insert data in the sheet on clicking the submit button
function insertInSS(e){
var mygrid = UiApp.getActiveApplication()
var name1 = e.parameter.name1
var message1 = e.parameter.message1
mygrid.getElementById('info').setVisible(true).setStyleAttribute('color','blue')
var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet()
var lastRow = sheet.getLastRow()
var targetRange = sheet.getRange(lastRow+1, 1, 1, 2).setValues([[name1,message1]])
return mygrid
}
Ahh! A simple fix for a big headache.
I had an extra line:
mygrid.add(grid);
that was breaking it.

Creating a table dynamically using Javascript

I am trying to create a table dynamically as soon as a page loads. In the code below, I get a response when I click the button, but the table is not displayed on the page. What's wrong with the code below? I have looked at other discussion threads on this topic, but none have helped.
The code in the Javascript file is as follows:
function showalert() {
alert('what?');
}
function displayGuides() {
var mgdCell, mgdRow, mgdTable;
mgdTable = document.createElement('table');
mgdRow = mgdTable.insertRow(0);
mgdCell = mgdRow.insertCell(0);
mgdCell.innerHTML = "1111";
mgdCell = mgdRow.insertCell(1);
mgdCell.innerHTML = "2222";
mgdCell = mgdRow.insertCell(2);
mgdCell.innerHTML = "3333";
mgdCell = mgdRow.insertCell(3);
mgdCell.innerHTML = "4444";
mgdCell = mgdRow.insertCell(4);
mgdCell.innerHTML = "5555";
document.getElementByID('mgdTable').appendChild(mgdTable);
}
function mgdUserActions() {
var create = document.getElementById('create');
create.onclick = showalert;
displayGuides();
}
window.onload = mgdUserActions;
Your call in displayGuides to document.getElementByID should be document.getElementById. The 'D' in ID should be 'd' Id.
Check out the fiddle of awesomeness

How to add a duplicate panel in google apps script?

I am wondering how to add a duplicate panel underneath the previous existing panel ("productOtherPanel") using the "Add Product" button. I would like the new panel to be inserted below the existing "productOtherPanel" and above the "Add Product" button. I would also like this new panel to contain the same drop down list and text box as the original "productOtherPanel". I need this panel to duplicate an infinite number of times. Is this possible?
function doGet(e) {
var app = UiApp.createApplication();
var productOtherPanel = app.createHorizontalPanel().setId('productOtherPanel');
var productPanel = app.createVerticalPanel().setId('productPanel');
var productList = app.createListBox().setName("productList").setId('productList');
productList.addItem("8:1 Compressed Blocks");
productList.addItem("8:1 Compressed Briquettes");
var pricePerTonPanel = app.createVerticalPanel().setId('pricePerTonPanel');
var pricePerTonTextBox = app.createTextBox().setId("pricePerTonTextBox").setName("pricePerTonTextBox")
.setText("$0.00");
var buttonPanel = app.createVerticalPanel().setId('buttonPanel');
var button = app.createButton("Add Product");
app.add(productOtherPanel);
productOtherPanel.add(productPanel);
productPanel.add(productList);
productOtherPanel.add(pricePerTonPanel);
pricePerTonPanel.add(pricePerTonTextBox);
app.add(buttonPanel);
buttonPanel.add(button);
return app;
}
Try to see if this code is what you are looking for:
function doGet(e) {
var app = UiApp.createApplication();
var productOtherPanel = app.createVerticalPanel().setId('productOtherPanel');
var productPanel = app.createHorizontalPanel().setId('productPanel');
// Product list dropdown
var productList = app.createListBox().setName("productList").setId('productList');
productList.addItem("8:1 Compressed Blocks");
productList.addItem("8:1 Compressed Briquettes");
// Product Price Textbox
var pricePerTonTextBox = app.createTextBox().setId("pricePerTonTextBox").setName("pricePerTonTextBox").setText("$0.00");
productPanel.add(productList);
productPanel.add(pricePerTonTextBox);
var buttonPanel = app.createVerticalPanel().setId('buttonPanel');
var button = app.createButton("Add Product");
button.addClickHandler(app.createServerHandler("addProductHandler").addCallbackElement(productOtherPanel));
app.add(productOtherPanel);
productOtherPanel.add(productPanel);
app.add(buttonPanel);
buttonPanel.add(button);
return app;
}
function addProductHandler(e) {
var app = UiApp.getActiveApplication();
var productPanel = app.createHorizontalPanel().setId('productPanel');
// Product list dropdown
var productList = app.createListBox().setName("productList").setId('productList');
productList.addItem("8:1 Compressed Blocks");
productList.addItem("8:1 Compressed Briquettes");
// Product Price Textbox
var pricePerTonTextBox = app.createTextBox().setId("pricePerTonTextBox").setName("pricePerTonTextBox").setText("$0.00");
productPanel.add(productList);
productPanel.add(pricePerTonTextBox);
var panel = app.getElementById("productOtherPanel");
panel.add(productPanel);
return app;
}

Categories