Skip to content

Instantly share code, notes, and snippets.

@sachith-gunasekara
Created January 29, 2023 18:42
Show Gist options
  • Save sachith-gunasekara/c752edac48cc5727f3c0984626c4f1fb to your computer and use it in GitHub Desktop.
Save sachith-gunasekara/c752edac48cc5727f3c0984626c4f1fb to your computer and use it in GitHub Desktop.
A Google Script function that can be used to populate dependent dropdowns
function onEdit(e) {
var ss = SpreadsheetApp.getActive();
var sampleDataSheet = ss.getSheetByName("sample_data");
var mohPhiDataSheet = ss.getSheetByName("moh_phi_data");
// Check if the active sheet is "sample_data" and the active cell is in the first column (MOH area)
if (ss.getActiveSheet().getName() == "sample_data" && e.range.getColumn() == 1) {
// Notify user of populating process
SpreadsheetApp.getActiveSpreadsheet().toast("Populating PHI Values")
var currRow = e.range.getRow();
var mohArea = e.range.getValue();
// Get the range of MOH areas and PHI areas in the "moh_phi_data" sheet
var mohRange = mohPhiDataSheet.getRange("B:B");
var phiRange = mohPhiDataSheet.getRange("C:C");
var mohValues = mohRange.getValues();
var phiValues = phiRange.getValues();
var phiAreaValues = [];
// Get the PHI area values that correspond to the selected MOH area
for (var i = 0; i < mohValues.length; i++) {
if (mohValues[i][0] == mohArea) {
phiAreaValues.push(phiValues[i][0]);
}
}
// Create data validation rule for PHI area dropdown
var phiAreaRule = SpreadsheetApp.newDataValidation().requireValueInList(phiAreaValues).build();
// Set the data validation rule for the PHI area cell in the current row
sampleDataSheet.getRange(currRow, 2).setDataValidation(phiAreaRule);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment