Filter a table with dropdown of a referenced database

Hi, I have a table showcasing company employees, with every employee taking a post from Posts database. Setting the table with attributes is fine, however, now I want to allow search for employees based on post. I set up the search with a dropdown, but for the matter it could also be a text search.
This is the code (for dropdown):

export function filterPost_change(event) {
//for posts database (there are more options)
dropdownFilter($w(‘#datasetPosts’), $w(‘#filterPost’).value, “postName”);
}

function dropdownFilter (dataset, value, reference) {
//Find the requested value in requested Database and put it on current item
//Then update main Database (EMPLOYEES) to include only items who include the specified item in their field for it
for ( var i = 0; i < dataset.getTotalCount() && dataset.getCurrentItem().title !== value; i++) {
//continue until found matching index
dataset.setCurrentItemIndex(i);
// console.log(dataset.getCurrentItemIndex());
}
// console.log(dataset.getCurrentItem());
var main = $w(‘#datasetEmployees’);
// main.setFilter(wixData.filter().contains(reference, dataset));
// $w(‘#table’).rows = main.getItems(); (I’m not sure if this is correct, didn’t get to it yet)
}

This code is PILOT. PROBLEM here is that when I run dataset.setCurrentItemIndex(i) and check the current index then on console log I find that it always stays at 0!!! for this I can’t set focus on the item I need! I tried using dataset.next() instead, but still same effect. Could you say how should I cange the function so it allows dropdown filter, perhaps from code that worked already? I already searched the forum and help but didn’t seem to find solution for a case of dropdown filter with reference.

Hi Michael,

You can replace the loop with a Query() function.
In order to find an item that include reference field you will have to use include() function also.
As a result, there is no need in setCurrentItemIndex() function because you already have the desirable item from the Query function.

import wixData from 'wix-data'; //This line supposed to be in the top of the page before the //onReady() function

//This function replace the for loop:
wixData.query("    The name of the database       ")
  .include(" The reference field( I believe is postName according to your example)", 
  "$w('#filterPost').value")
  .find()
  .then( (results) => {
        let main = $w('#datasetEmployees');   
        main.setFilter(wixData.filter().contains(reference, results.items[0]));  // 
        $w('#table').rows =  main.getItems();  
        
    } 
  } );

Here you can read more about Query() function:

Beat,
Sapir