Data Validation range from different spreadsheets - validation

I have in my main spreadsheet a dropdown with data validation of a range from another tab in the same spreadsheet with data imported from another spreadsheet or with IMPORTRANGE function or imported with a script.
In both cases the main spreadsheet is very slow cause I have a lot of tab with data imported with both methods.
There is a way to do the data validation of the dropdown in the main sheet taking the data I need directly from the other spreadsheets without import them previously in the main spreadsheet with the IMPORTRANGE function or with a script?
I have tried to write a draft script but not works:
function externalSheetDataValidation() {
var cell = SpreadsheetApp.getActiveRange();
var dataValidationSheet = SpreadsheetApp.openById("xxxxxxxxxx");
var sheet = dataValidationSheet.getSheets()[0];
var range = sheet.getRange("B2:B5000");
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(range, true)
.setAllowInvalid(false)
.build();
cell.setDataValidation(rule);
Logger.log(dataValidationSheet.getName());
}

You want to populate a dropdown based on the values of a range from a different spreadsheet.
You are currently importing those values to a sheet in your spreadsheet in order to use them via requireValueInRange.
You would like to skip the import process.
If that's the case, you can just do the following:
Create a function that returns a simple array with the values from the source range:
function importSheetA() {
return SpreadsheetApp.openById('xxxxx')
.getSheetByName('xxxxx')
.getRange('xxxxx')
.getValues()
.flat(); // This ensures a simple array is returned
}
Populate the dropdowns with requireValueInList instead of requireValueInRange, using the values returned by importSheetA:
function populateDropdown() {
var values = importSheetA();
var rule = SpreadsheetApp.newDataValidation()
.requireValueInList(values, true)
.setAllowInvalid(false)
.build();
var range = SpreadsheetApp.getActiveRange();
range.setDataValidation(rule);
}
Note:
You could update the populated options when the source range is edited if you install an onEdit trigger, and you could also specify what range of cells should be populated with dropdowns without them being necessarily selected, but I'm not sure that's what you want.
Update:
If your data has more than 500 items, value in list criteria is not an option. Your only other option would be to use List from a range instead, but as you said, this would require the source range to be on the same spreadsheet as the dropdown, which you wanted to avoid.
As a workaround, I'd suggest you to programmatically copy the data to a hidden sheet in the target spreadsheet, and use the data in this hidden sheet as your source range when creating the dropdown. For example, this:
function copyRange() {
var cell = SpreadsheetApp.getActiveRange();
var rangeNotation = "B2:B5000"; // Change according to your preferences
var sourceData = SpreadsheetApp.openById(xxxxx)
.getSheetByName(xxxxx)
.getRange(rangeNotation)
.getValues();
var targetSS = SpreadsheetApp.getActiveSpreadsheet();
var hiddenSheetName = "Hidden source data"; // Change according to your preferences
var hiddenSheet = targetSS.getSheetByName(hiddenSheetName);
if (!hiddenSheet) hiddenSheet = targetSS.insertSheet(hiddenSheetName);
var sourceRange = hiddenSheet.getRange(rangeNotation);
sourceRange.setValues(sourceData);
hiddenSheet.hideSheet();
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.setAllowInvalid(false)
.build();
cell.setDataValidation(rule);
}
Reference:
requireValueInList(values, showDropdown)

Cached Dropdown Dialog
GS:
function getSelectOptions(){
const cs=CacheService.getScriptCache();
const v=JSON.parse(cs.get('cached'));
if(v){return v;}
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Options');
var rg=sh.getDataRange();
var vA=rg.getValues();
var options=[];
for(var i=0;i<vA.length;i++)
{
options.push(vA[i][0]);
}
cs.put('cached', JSON.stringify(vA), 300)
return vA;
}
function showMyselectionDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah2'), 'Selections');
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
google.script.run
.withSuccessHandler(function(vA) {
updateSelect(vA);
})
.getSelectOptions();
function updateSelect(vA,id){//the id allows me to use it for other elements
var id=id || 'sel1';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
<body>
<select id='sel1'></select>
</body>
</html>

Related

google form script exclude sundays on dates choices

im making a script for making an apointment. I get the choices of appointmentt date from my spreadsheet using script. How to exclude sunday when i get the choices from my spreadsheet ? i cant find a way to remove the sunday.
here is the code
var ssID = "1hil07Z2wvTXH1szX9bNfPKVLDQVO36ACQFGOU6_VUI0";
var formID="1SD5BenAnNxNz-wtw0YPut6YdTf7a62zHn_z3VrTdTUU";
var wsData = SpreadsheetApp.openById(ssID).getSheetByName("DATA");
var form = FormApp.openById(formID);
function main(){
var labels = wsData.getRange(1,1,1,wsData.getLastColumn()).getValues()[0];
labels.forEach(function(label,i){
var options = wsData
.getRange(2, i+1,wsData.getLastRow()-1,1)
.getDisplayValues()
.map(function(o){return o[0]})
.filter(function(o){return o !== ""})
//Logger.log(options);
updateDropDownUsingTitle(label,options);
});
}
function updateDropDownUsingTitle(title,values) {
var title = "Tanggal Penjemputan";
var items = form.getItems();
var titles = items.map(function(item){
return item.getTitle();
});
var pos = titles.indexOf(title);
var item = items[pos];
var itemID = item.getId();
updateDropdown(itemID,values);
}
function updateDropdown(id,values) {
var item = form.getItemById(id);
item.asListItem().setChoiceValues(values);
}
this is the form
THis is my spreadsheet
There are 3 ways to achieve your goal:
Use a non-Sunday formula in sheet
Add a weekday column to sheet and filter in script
getValues and new Date instead of getDisplayValues, filter Sunday and then Utilities.formatDate
You can use the following formula:
=ArrayFormula(TODAY()+FILTER({1;2;3;4;5;6;7}, WEEKDAY(TODAY()+{1;2;3;4;5;6;7})<>1))
See on Google Sheets
This will give you the next 7 days excluding Sunday.

A simple sort script on Google Sheets is not working

I have a "leaderboard"/"scoreboard", across four sheets, that I need to have auto sorting whenever updated by first Total Score (column 2) and then Total Kills (column 3). These columns are the same across all four sheets.
I've used a very simple script in the past when the scoreboard was limited to one sheet, but I have since expanded it to have Top Ten, Top Four, and Top Two on separate sheets within the same document.
The problem I'm running into: When the script updates one sheet, the other ones seem to flat out stop working entirely; in other words, the script breaks.
Can I please get some advice? I've tried several scripts already from this site, and the basic one I see some success with (but then the script seemingly breaks?) is below.
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MAIN EVENT");
sheet.sort(3, false).sort(2, false);
}
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP TEN");
sheet.sort(3, false).sort(2, false);
}
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP FOUR");
sheet.sort(3, false).sort(2, false);
}
function sortOnEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TOP TWO");
sheet.sort(3, false).sort(2, false);
}
Ideally, when functioning, the sheets will literally just sort themselves by the Total Score column, with Total Kills being the "tiebreaker" for sorting.
I've included a copy of my sheet if anybody could help:
https://docs.google.com/spreadsheets/d/1a6XGv09TPt5Vnxqfcd1Xba3TGMis5OelGxlvzNDl5CY/edit?usp=sharing
try something like this instead of your scripts:
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = event.source.getActiveSheet().getName()
var editedCell = event.range.getSheet().getActiveCell();
if(sheet=="Sheet1"){
var columnToSortBy = 2;
var tableRange = "A3:C10"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}}
else if(sheet=="Sheet2"){
var columnToSortBy = 7;
var tableRange = "A3:C10"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
else{return}
}}
try this:
function sortOnEdit(e) {
var sh=e.range.getSheet();
var name=sh.getName();
var incl=['MAIN EVENT','TOP TEN','TOP FOUR','TOP TWO'];
if(incl.indexOf(name)==-1) return;
sh.sort(3,false).sort(2,false);
}

Dropdown menu with OpenLayers 3

I am using openlayers 3. From the values contained in a vector GeoJSON, I want to fill a dropdown menu. When selecting a value from the dropdown menu, I want to zoom in on the entity.
My problem now is that I want to generate my HTML from the attributes of my GeoJSON. So I tried this simple code but it doesn't work :
var menu = document.getElementById('menuDropDown');
vector2.getSource().forEachFeature(function() {
menu.innerHTML = feature.get('NOM').join(', ');
});
EDIT:
I'm able to populate a dropdown menu from a list:
var list = ['a','b','c'];
var mySelect = $('#mySelect');
$.each(list, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
What i want to do it's to populate this list from the attribute of my vector
So i try this:
// vector2 it's a GeoJSON who is integrate on my map
vector2.getSource().getFeatures().forEachFeature(function(feature) {
list.push(feature.get('NOM'));
});
Firstly I'm assuming you have to pass some parameter to your callback:
vector2.getSource().forEachFeature(function(feature) {
Then you can append an item to a dropdown like so:
var item = document.createElement('option');
item.setAttribute('value', feature.get('NOM'));
var textNode = document.createTextNode(feature.get('NOM'));
item.appendChild(textNode)
menu.appendChild(item);
All together:
var menu = document.getElementById('menuDropDown');
vector2.getSource().forEachFeature(function(feature) {
var item = document.createElement('option');
item.setAttribute('value', feature.get('NOM'));
var textNode = document.createTextNode(feature.get('NOM'));
item.appendChild(textNode)
menu.appendChild(item);
});
I have resolve my problem:
vector2.getSource().on('change', function(evt){
var source = evt.target;
var list = [];
source.forEachFeature(function(feature) {
list.push(feature.get('NOM'));
});
// console.log("Ecrit moi les noms : " + list);
Thanks you to those who took the time to respond

Google apps script UI services to HTML services

I try to convert this simple google apps script code below to HTML services code.
The code below is written with the deprecated google apps script UI services!
Can anyone help me with HTML services example code in this usecase?
// Script with deprecated UI-services
// How to create this app with HTML-services?!!!?
//This script runs in a google website.
//It has one textobject and 1 button.
//when the button is pressed the value entered is stored in the spreadsheet
ssKey = 'sheetkey....';
function doGet(){
var app = UiApp.createApplication().setTitle('myApp');
//Create panels en grid
var MainPanel = app.createVerticalPanel();
var Vpanel1 = app.createVerticalPanel().setId('Vpanel2');
var grid = app.createGrid(4, 2).setId('myGrid');
//Vpanel1 widgets
var nameLabel = app.createLabel('Name');
var nameTextBox = app.createTextBox().setWidth('400px').setName('name').setId('name');
var submitButton = app.createButton('Verstuur').setId('submitButton');
grid.setWidget(0, 0, nameLabel)
.setWidget(0, 1, nameTextBox)
.setWidget(1, 1, submitButton);
//Set handlers en callbackelement
var handler = app.createServerClickHandler('InsertInSS');
handler.addCallbackElement(Vpanel1);
submitButton.addClickHandler(handler);
// build screen
Vpanel1.add(grid);
app.add(Vpanel1);
return app;
}
function InsertInSS(e){
var app =UiApp.getActiveApplication();
var collectedData = [new Date(), e.parameter.name] ;
var SS = SpreadsheetApp.openById(ssKey);
var Sheet = SS.getSheetByName('Contacts');
Sheet.getRange(Sheet.getLastRow()+1, 1, 1, collectedData.length).setValues([collectedData]);
app.getElementById('submitButton').setVisible(false);
//Reset fields on screen
app.getElementById('name').setText("");
return app;
}
Your Ui output looks like this:
Create an HTML file, and enter this code:
testForm.html
<div>
<div>
Name: <input id='idNameField' type='text'/>
</div>
<br/>
<input type='button' value='Verstuur' onmouseup='runGoogleScript()'/>
</div>
<script>
function onSuccess(argReturnValue) {
alert('was successful ' + argReturnValue);
//Reset fields on screen
Document.getElementById('idNameField').value = "";
}
function runGoogleScript() {
console.log('runGoogleScript ran!');
var inputValue = document.getElementById('idNameField').value;
google.script.run.withSuccessHandler(onSuccess)
.InsertInSS(inputValue);
};
</script>
Copy the follow code into:
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('testForm')
.evaluate() // evaluate MUST come before setting the NATIVE mode
.setTitle('The Name of Your Page')
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};
In a seperate .gs file add this code:
function InsertInSS(argPassedInName){
var ssKey = 'sheetkey....';
var SS = SpreadsheetApp.openById(ssKey);
var Sheet = SS.getSheetByName('Contacts');
Sheet.getRange(Sheet.getLastRow()+1, 1, 1, argPassedInName.length).setValue(argPassedInName);
}

Assigning functions to multiple slickgrids

Please help to solve this very annoying problem. I am using a for loop to iterate over an array of data and create multiple grids. It is working well but the filter function is not binding properly (it only binds to the LAST grid created) Here is the code:
// this function iterates over the data to build the grids
function buildTables() {
// "domain" contains the dataset array
for (i = 0; i < domains.length; i++) {
var dataView;
dataView = new Slick.Data.DataView();
var d = domains[i];
grid = new Slick.Grid('#' + d.name, dataView, d.columns, grids.options);
var data = d.data;
// create a column filter collection for each grid - this works fine
var columnFilters = columnFilters[d.name];
// this seems to be working just fine
// Chrome console confirms it is is processed when rendering the filters
grid.onHeaderRowCellRendered.subscribe(function (e, args) {
$(args.node).empty();
$("<input type='text'>")
.data("columnId", args.column.id)
.val(columnFilters[args.column.id])
.appendTo(args.node);
});
// respond to changes in filter inputs
$(grid.getHeaderRow()).delegate(":input", "change keyup", function (e) {
var columnID = $(this).data("columnId");
if (columnID != null) {
// this works fine - when the user enters text into the input - it
// adds the filter term to the filter obj appropriately
// I have tested this extensively and it works appropriately on
// all grids (ie each grid has a distinct columnFilters object
var gridID = $(this).parents('.grid').attr('id');
columnFilters[gridID][columnID] = $.trim($(this).val());
dataView.refresh();
}
});
//##### FAIL #####
// this is where things seem to go wrong
// The row item always provides data from the LAST grid populated!!
// For example, if I have three grids, and I enter a filter term for
// grids 1 or 2 or 3 the row item below always belongs to grid 3!!
function filter(row) {
var gridID = $(this).parents('.grid').attr('id');
for (var columnId in grids.columnFilters[gridID]) {
if (columnId !== undefined && columnFilters[columnId] !== "") {
var header = grid.getColumns()[grid.getColumnIndex(columnId)];
//console.log(header.name);
}
}
return true;
}
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
dataView.setFilter(filter); // does it matter than I only have one dataView instance?
dataView.endUpdate();
grid.invalidate();
grid.render();
In summary, each function seems to be binding appropriately to each grid except for the filter function. When I enter a filter term into ANY grid, it returns the rows from the last grid only.
I have spent several hours trying to find the fault but have to admit defeat. Any help would be most appreciated.
yes, it matters that you have only one instance of dataView. and also sooner or later you will come up to the fact that one variable for all grids is also a bad idea
so add a var dataView to your loop, it should solve the problem

Resources