@dustin in that case productFilter must be refined a bit. The idea is to only apply a condition to Dataset filter if dropdown value is not empty:
async function productFilter() {
let filter = wixData.filter()
if ($w('#dropdown1').value) {
filter = filter.eq('model', $w('#dropdown1').value)
}
if ($w('#dropdown2').value) {
filter = filter.eq('year', $w('#dropdown2').value)
}
const selectedCategoryIndex = $w("#dropdown3").selectedIndex
if (selectedCategoryIndex) {
const categories = (await $w("#dataset2").getItems(0, 20)).items
const selectedCategoryId = categories[selectedCategoryIndex]._id
filter = filter.eq('category', selectedCategoryId)
}
const selectedSubCategoryIndex = $w("#dropdown4").selectedIndex
if (selectedSubCategoryIndex) {
const subCategories = (await $w("#dataset3").getItems(0, 20)).items
const selectedSubCategoryId = subCategories[selectedSubCategoryIndex]._id
filter = filter.eq('subCategory', selectedSubCategoryId)
}
$w('#dataset1').setFilter(filter)
}
However, this function is getting a bit clunky and repetitive. By creating several more generic functions, we can clean it up considerably. Let’s start with a function which extracts a value from dropdown and applies filter condition if the value exists:
function addConditionIfDropdownSelected(filter, dropdownId, fieldKey) {
const value = $w('#' + dropdownId).value
if (value) {
return filter.eq(fieldKey, value)
}
return filter
}
Next, let’s do the same for dropdowns populated by references:
async function addConditionIfReferenceDropdownSelected(filter, datasetId, dropdownId, fieldKey) {
const selectedValueIndex = $w('#' + dropdownId).selectedIndex
if (selectedValueIndex !== undefined) {
const items = (await $w('#' + datasetId).getItems(0, 20)).items
const selectedItemId = items[selectedValueIndex]._id
return filter.eq(fieldKey, selectedItemId)
}
return filter
}
And then filterProducts can be rewritten as follows:
async function productFilter() {
let filter = wixData.filter()
filter = addConditionIfDropdownSelected(filter, 'dropdown1', 'model')
filter = addConditionIfDropdownSelected(filter, 'dropdown2', 'year')
filter = await addConditionIfReferenceDropdownSelected(filter, 'dataset2', 'dropdown3', 'category')
filter = await addConditionIfReferenceDropdownSelected(filter, 'dataset3', 'dropdown4', 'subCategory')
$w('#dataset1').setFilter(filter)
}