I am having some trouble with Velo and filtering a gallery with selection tags. I would like the gallery to be filtered by a specific tag when the page loads. Currently the gallery is unfiltered when the page loads.
In my current code I have achieved reordering the selection tags and selecting the first.
I still need the connected gallery to filter the items according to the selected indices on page load. I would greatly appreciate any help
You need to set the gallery’s data after you set your selected indices.
If you already have all your items in your gallery you can first retrieve the items by using this line
let items = $w("#myGallery").items;
/*
This will return an array of objects. The objects will consist of any
of the following as show in the [documentation](https://www.wix.com/velo/reference/$w/gallery/shownavigationbuttons).
*/
Then you can filter your gallery items to match what your filter is. When using two arrays to filter one another, I prefer to use .some. So in this case, your selection tags value and label is the same. So let’s simplify by only mapping the values. You can either use .map() or just do:
let currentSelections = $w("#selectionTags1").value
// this will return something like ["Maling", "Beis"]
So now that we have the values that are selected and our gallery list of items, we now need to filter them. If your gallery is connected to the content manager, you would need to have some sort of values associated so we know to filter certain item with certain tags. If your items are not connected to a database and you just preloaded them into the gallery then we need to adjust your object schema. If it’s the latter, you can edit my first code line to be the following:
let items = $w("#myGallery").items;
items = items.map((gallery) => ({
...gallery, // let's keep the structure
color: 'Brown' // realistically you need this "color" to be unique to each item... Strongly suggest organizing this in your CMS.
}))
Now we can use the .some function which will compare the list of all of our items any only select the ones needed that is logged with your selection tags array
const useThese = items.filter((all) => {
return currentSelections.some((exists) => {
return exists === all.color // change this to the object key needed
});
});
lastly you set your items. You can also make the .some function into an event handler and just call it on load if you have coded in an onchange event handler for your selection tags.
// set your gallery
$w('myGallery1').items = useThese