I am constructing a mobile page for a store using a repeater instead of using the standard layouts from the Store app, as my client wants two columns of products on-screen on a phone…and the standard app layout defaults to one column on mobile.
I pull the data from the collection in code, and can display it fine. I then want to be able to add a filter for Collections, as referenced in the multi-ref field in Products.
I’ve read everything I can find to figure out how to do this in code but cannot figure out how to code it…the direction in the API docs just confuses me more.
This sets the page up fine but how can I set up a filter from here, using the value from a dropdown menu?? I can grab the value fine, but what do I do with it to filter the data?
I really need some detailed coding guidance on how to re-filter allProducts by Collection…can anyone help??
I grab the ID from the Collections collection that matches the category that I am looking for (the one in my dropdown menu on the page):
let lookupIds = await wixData.query("Stores/Collections").contains("name",$w('#FilterDropDown').value).find().then((results)=>{return results.items});
let categoryId = lookupIds[0]._id;
Then I modified the query to pull only when that ID is in the Products collection:
let allProducts = await wixData.query("Stores/Products").eq("collections", categoryId).limit(100).find().then((results)=>{return results.items})
I’ll probably run that first query when the site first loads and store it locally, to avoid having to run two queries to load this page.
You can save yourself the added step of running a query to find the collection’s id by mapping it to the dropdown when you populate the options.
wixData.query('Stores/Collections')
.find()
.then(res => {
//Add an All Collections option
let options = [{ 'value': '', 'label': 'All Collections' }];
//Map the options to an object using the collection's id as the value
options.push(...res.items.map(collection => {
return { 'value': collection._id, 'label': collection.name };
}));
//Set the filter drowndown's options to the newly created options object
$w('#collectionDropdown').options = options;
});
//************************ IF USING CODE TO POPULATE PRODUCT REPEATER
$w("#collectionDropdown").onChange(async()=>{
let results = await wixData.query("Stores/Collections").eq("collections", $w("#collectionDropdown").value).find();
})
//*********************** IF USING DATASET TO POPULATE PRODUCT REPEATER
$w('#collectionDropdown').onChange((event) => {
let newFilter = wixData.filter();
newFilter = newFilter.eq('collections', $w('#collectionDropdown').value);
$w('#dataset1').setFilter(newFilter);
});