I have a strange problem in my code. I want to get an item from store by its id. the value of itemId is 1 and I get null for firstItem.
var itemId = dragIdSplit[1];
var firstItem = me.getPStore().getById(itemId);
Then if I just call getById(1) the correct value will be returned. Can someone help me with this issue?
try below changes. you doing split so it's a string you have to convert it into integer.
var itemId = parseInt( dragIdSplit[1]);
var firstItem = me.getPStore().getById(itemId);
Related
So, I have been asked to rephrase my question post. I actually thought it would make sense if I shared a picture of what I need to accomplish. My apologies for not knowing the format. But anywho ...
Required:
I have a spreadsheet file and a user enters a value in a specific cell (see picture below). I want that value be stored along with the current date in a two dimensional array.
What my code does: This code is
(1) Using a PropertiesService to store a value globally
(2) Accepting user input in H3 cell and is updating J3 cell with a date of format mm/dd and appending the user input. For e.g., if user inputs 4 in H3 and current date is 8/29/2019, then J3 will display "8/29::4"
(3) This code also adds a comment with the above value in H3
Error/Issue
(1) When I try to declare an array in the onEdit function and attempt to write something into it, it is spitting this error:
TypeError: Cannot read property 'push' of undefined
at onEdit(Code:21:29)
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('i', 0);
function onEdit(e){
if (e.range.getA1Notation() == "H3")
{
var difference = isNaN(e.value) ? 0 : Number(e.value);
var date = (new Date());
var monthValue = date.getMonth();
var dateValue = date.getDate();
var wholeValues = [];
monthValue = monthValue+1;
dateValue = dateValue-1;
var logTimestamp = monthValue+"/"+dateValue;
e.range.getSheet().getRange("J3").setValue(logTimestamp+"::"+difference+";");
e.range.setNote(logTimestamp+"::"+difference+";");
var arrayIndex = Number(scriptProperties.getProperty('i'));
wholeValues[arrayIndex].push("Sample Data");
arrayIndex = arrayIndex + 1;
Logger.log("wholeValues size is " +wholeValues.length);
}
}
Issues:
wholeValues array is local and won't persist across sessions/function calls/script runs.
wholeValues is a empty array all the time.
i will always be "0" as you're setting it to 0 in global scope each time a function is called.
wholeValues[0](=[][0]) is undefined as there is no element with index 0. undefined doesn't have .push function. Therefore, Cannot read property 'push' of undefined
Solution:
Different approaches can be made:
Create a object dateObj with value {date1:value1,date2:value2,...} and store it in properties as a string.
Set the datestring itself as a key to properties. Here each property is object containing {date:value}
You can save the array in a log sheet.
Snippet:
/*var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('i', 0);*/ //Removed from global scope
function onEdit(e){
if (e.range.getA1Notation() == "H3")
{
/* Rest of your code*/
e.range.setNote(logTimestamp+"::"+difference+";");
var scriptProperties = PropertiesService.getScriptProperties();
var dateObjStr = scriptProperties.getProperty('dateObj');
var dateObj = dateObjStr ? JSON.parse(dateObjStr) : {};
var dateStr = Utilities.formatDate(date, e.source.getSpreadsheetTimeZone(), "YYYY-MM-dd");
dateObj[dateStr] = difference;//{"2019-08-28": 6}
scriptProperties.setProperty('dateObj', JSON.stringify(dateObj));
}
}
Snippet#2:
var scriptProperties = PropertiesService.getScriptProperties();
var dateStr = Utilities.formatDate(date, e.source.getSpreadsheetTimeZone(), "YYYY-MM-dd");
scriptProperties.setProperty(dateStr, difference);
var dateVal = scriptProperties.getProperty(dateStr) || 0; //Retrieval
Snippet#3:
var dateStr = Utilities.formatDate(date, e.source.getSpreadsheetTimeZone(), "YYYY-MM-dd");
e.source.getSheetByName('LogSheet').appendRow([dateStr, difference]);
References:
Quotas
Properties value size 9kB / val
Properties total storage 500kB / property store
Properties read/write 50,000 - 500,000/ day
PropertiesService
Utilities#formatDate
I have a solution for filtering on this question.
This works perfectly with a column that has string values. When I try to filter a column with numeric values it will not work. I'm assuming it is because .setHiddenValues() will not accept numeric values. I could be wrong.
Let me explain my scenario:
The user inputs a value on an HTML interface, let's say 6634.
The HTML calls my function on .gs and passes the numeric value the user inputted.
google.script.run //Executes an Apps Script JS Function
.withSuccessHandler(updateStatus) //function to be called upon successfull completion of Apps Script function
.withFailureHandler(failStatus)
.withUserObject(button) //To pass the event element object
.projectSearch2(projectID); //Apps Script JS Function
return;
The function (on the linked question above) will take that value and bump it up against the values in a column deleting the value if it is found. What I am left with is an array of values that I do not want filtered.
function projectSearch2(projectID){
var ss = SpreadsheetApp.getActive();
var monthlyDetailSht = ss.getSheetByName('Data Sheet');
var monLastCN = monthlyDetailSht.getLastColumn();
var monLastRN = monthlyDetailSht.getLastRow();
var data = monthlyDetailSht.getRange(1,1,1,monLastCN).getValues();//Get 2D array of all values in row one
var data = data[0];//Get the first and only inner array
var projectIDCN = data.indexOf('Project Id') + 1;
//Pull data from columns before filtering
var projectIDData = monthlyDetailSht.getRange(2,projectIDCN,monLastRN,1).getValues();
//Reset filters if filters exist
if(monthlyDetailSht.getFilter() != null){monthlyDetailSht.getFilter().remove();}
//Start Filtering
var projectIDExclCriteria = getHiddenValueArray(projectTypeData,projectID); //get values except for
var rang = monthlyDetailSht.getDataRange();
var projectIDFilter = SpreadsheetApp.newFilterCriteria().setHiddenValues(projectIDExclCriteria).build();//Create criteria with values you do not want included.
var filter = rang.getFilter() || rang.createFilter();// getFilter already available or create a new one
if(projectID != '' && projectID != null){
filter.setColumnFilterCriteria(projectIDCN, projectIDFilter);
}
};
function getHiddenValueArray(colValueArr,visibleValueArr){
var flatUniqArr = colValueArr.map(function(e){return e[0];})
.filter(function(e,i,a){return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) ==-1); })
return flatUniqArr;
}
That array is used in .setHiddenValues() to filter on the column.
Nothing is filtered however. This works for all columns that contain string values, just not columns with numeric values. At this point I'm lost.
Attempted Solutions:
Convert user variable to string using input = input.toString(). Did not work.
manually inserted .setHiddenValues for projectIDExclCriteria. Like this: var projectIDFilter = SpreadsheetApp.newFilterCriteria().setHiddenValues([1041,1070,1071,1072]).build(); That succeeded so I know the issue is before that.
Step before was calling getHiddenValueArray. I manually inserted like so: var projectIDExclCriteria = getHiddenValueArray(projectIDData,[6634]); It is not working. Is the issue with that getHiddenValueArray function not handling the numbers properly?
Here is a solution. Changing the following:
.filter(function(e,i,a){return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) ==-1); })
To:
.filter(function(e,i,a){return (a.indexOf(e) == i && visibleValueArr.indexOf(e) == -1); })
That works! Thank you Tanaike. The next question is will this impact columns that are not numeric. I have tested that and it works as well.
How about this modification?
From :
.filter(function(e,i,a){return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) ==-1); })
To :
.filter(function(e,i,a){return (a.indexOf(e) == i && visibleValueArr.indexOf(e) == -1); })
Note :
In this modification, the number and string can compared using each value.
If you want to use return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) ==-1), you can achieve it by modifying from colValueArr.map(function(e){return e[0];}) to colValueArr.map(function(e){return e[0].toString();}).
In this modification, colValueArr.map(function(e){return e[0].toString();}) converts the number to string, so the number is used as a string.
Reference :
Array.prototype.indexOf()
I have a strange error occurring in an Apps Script function attached to a Google Form.
I call the responses, then list them in an array. The log shows that there are 6 items in the array, which matches the six form questions:
[18-05-08 00:13:31:900 AEST] [ItemResponse, ItemResponse, ItemResponse, ItemResponse, ItemResponse, ItemResponse]
When I call the first two, it works just fine. Any more and it bugs out and says undefined.
// Open a form by ID and log the responses to each question.
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var editUrl = String(formResponse.getEditResponseUrl());
var theResponseId = formResponses.indexOf(form);
var itemResponses = formResponse.getItemResponses();
var timestamp = formResponse.getTimestamp();
var firstName = itemResponses[0].getResponse();
var lastName = itemResponses[1].getResponse();
Logger.log(itemResponses); // Log shows there are 6 objects in the array. Matching the amount of Form Questions.
// If I try to use these variables below, it doesn't work and the script 'breaks' at this point.
//var number = itemResponses[2].getResponse();
//var email = itemResponses[3].getResponse();
//var firstName2 = itemResponses[4].getResponse();
//var comments = itemResponses[5].getResponse();
}
Note: I have tried FormApp.openById('id'); to see if maybe getting the active form was a problem. This didn't help.
This is because some answers were submitted to a 2 question form. If you submitted some responses prior to updating the form, the answers to these new questions will be "undefined".
I am trying to select a specific entry from a JSON but can not solve how to do it. The JSON that I get from the server (can not be modified) is:
[{"cid":"PWER","data":[{"1458496671000":464}],"sid":"728834","units":"kWm","age":0}]
What I need to get is the 464 (Power in Watts). The problem is, that the key is a timestamp and changes all the time. So far I tried
json[0].data[0]
but this leaves me with
{ '1458496779000': 464 }
Any ideas how I select the next value?
Thanks a lot!
You can do this -
var obj = json[0].data[0];
var key = Object.keys(obj)[0];
var data = obj[key];
// data is your value which should be 464.
This is the outcome I am looking for:
$scope.donotShow = false;
The way I want to get it is in the controller in which I have one variable to work with:
var slug = "donot";
I would like to combine it with the string "Show":
var slugshow = slug + "Show";
From here I want the outcome I am looking for but this does not work:
$scope.slugshow = false;
How do I make the var slugshow show as "donotShow" thus giving me
$scope.donotShow = false;