Velo Tutorial: Adding Collection Data Search Functionality
With Velo you can add a database collection to your site and display the data in many ways. Visitors to your site can also search that data. You can add this search functionality to your site by adding user input elements to the page and then adding some code to enable the search.
There are different ways you can let your visitors search your collection. This article covers the following options:
- Adding an input field where visitors enters a search string.
- Adding a dropdown list where visitors select a value from a list.
While the results can be displayed however you want them to appear on the page, in this article we'll cover how to display the data in a table. At the end of the tutorial we'll also cover how to optionally collapse the table until you are ready to display the results.
Search Using an Input Element
1. Add the input, button, and table elements to the page
- Add an input box, a button, and a table to your page.
You can customize them as you like. For example, you could change the text of the button to "Search" and configure the placeholder text of the input box to read "Search recipes." - Consider changing the IDs of each element that you just added to make them meaningful.
2. Add the code for inputting a search string
1. Add the import statement for the Wix Data API to the top of your code:
1import wixData from "wix-data";
1export function searchButton_click(event) {
2 //Add your code for this event here:
3}
- Replace existing text with the following code:
1// Runs a query on the "recipes" collection
2wixData.query("recipes")
3 // Query the collection for any items whose "Name" field contains
4 // the value the user entered in the input element
5 .contains("name", $w("#searchBox").value)
6 .find() // Run the query
7 .then(res => {
8 // Set the table data to be the results of the query
9 $w("#resultsTable").rows = res.items;
10 });
11
3. Define the table columns
1$w.onReady(function () {
2 $w("#resultsTable").columns = [
3 {
4 "id": "col1", // ID of the column for code purposes
5 // The field key in the collection whose data this column displays
6 "dataPath": "field1",
7 "label": "Field 1", // The column header
8 "width": 100, // Column width
9 "type": "string", // Data type for the column
10 // Path for the column if it contains a link
11 "linkPath": "link-field-or-property"
12 },
13 {
14 "id": "col2",
15 "dataPath": "field2",
16 "label": "Field 2",
17 "visible": true,
18 "type": "image",
19 "linkPath": "link-field-or-property"
20 } //,
21 // more column objects here if necessary
22 // ...
23 // ...
24 }];
25});
1$w.onReady(function () {
2 $w("#resultsTable").columns = [{
3 "id": "col1",
4 "dataPath": "title",
5 "label": "Recipe",
6 "type": "string",
7 }, {
8 "id": "col2",
9 "dataPath": "course",
10 "label": "Course",
11 "type": "string",
12 }, {
13 "id": "col3",
14 "dataPath": "meal",
15 "label": "Meal",
16 "type": "string",
17 }];
18});
wixData.query("recipes")
- Replacerecipes
with the name of your collection..contains("name", $w("#searchBox")
- Replacename
with the field key of the field in the collection that is being searched. ReplacesearchBox
with the element ID of your input box where visitors enter the string to search.$w("#resultsTable")
- ReplaceresultsTable
with the element ID of your table that displays the search results."dataPath value"
- Replace with the field keys in your collection.
Filter Using a Dropdown Element
1. Add the dropdown and table elements to the page
- Add a dropdown list element and a dataset to your page. Make sure the dataset is set to Read mode or Read & Write mode.
- In the Connect Dropdown panel, under the Connect a List section:
- Select the Connect dropdown list items toggle.
- Connect the list to a dataset connected to your collection.
- Under Labels and values connect to, select the field of the column you want to use as the options for the dropdown.
- Add a table element to your page.
2. Add the code for the dropdown selection to filter the collection
1. Add the import statement for the Wix Data API to the top of your code:
1import wixData from "wix-data";
1export function searchList_change(event) {
2 //Add your code for this event here:
3}
- Replace existing text with the following code:
1// Runs a query on the "recipes" collection
2wixData.query("recipes")
3 // Query the collection for any items whose "Name" field contains
4 // the value the user selected in the dropdown
5 .contains("course", $w("#myDropdown").value)
6 .find() // Run the query
7 .then(res => {
8 // Set the table data to be the results of the query
9 $w("#resultsTable").rows = res.items;
10 });
11
3. Define the table columns
Filter Dropdown Options Distinctly
We do not, however, want to display duplicate course values in the dropdown's options. We want each dropdown option to be distinct from the others.
First, we modify the dropdown we already added by disconnecting it from the collection in the Editor. We then add code to populate the options directly from the collection.
1. Disconnect the dropdown from the collection
- Select the dropdown list element on your page.
- In the Connect Dropdown panel, under the Connect a List section, toggle the Connect dropdown list items off.
- Make sure Choose is the value for Connect a dataset, and Not Connected is the value for Value connects to.
2. Add code to populate the dropdown with distinct options
We now add a function to populate our dropdown using distinct
function. We call this function loadOptions()
.
The distinct()
function queries the collection and returns field values that do not contain duplicates.
To populate the dropdown, the distinct query results have to be formatted as an array of strings in a certain format. loadOptions()
calls the buildOptions()
function for this purpose.
This example also demonstrates how to insert an extra All Courses option to our dropdown so users can reset the filter from the dropdown.
You can copy the following code for these functions directly into your page code. You need to replace the element IDs and the collection name with those in your site.
1function loadOptions() {
2
3 // Run a query that returns distinct items in the collection
4 wixData.query("recipes")
5
6 // Set the course as the field that must be distinct
7 .distinct("course")
8
9 .then(results => {
10
11 // Call another function to reformat the distinct items
12 // the way the dropdown element expects
13 let distinctList = buildOptions(results.items);
14
15 // Use `unshift()` to add another dropdown option at
16 // the beginning of the array, in the correct format
17 distinctList.unshift({ "value": '', "label": 'All Continents' });
18
19 // Set the options of the dropdown
20 $w("#myDropdown").options = distinctList;
21
22 });
23
24}
Let's now code the loadOptions()
function. This function takes each distinct item from the collection and reformats the option in the format expected by the dropdown:
{ "label": "uniqueTitle", "value": "uniqueTitle" }
1function buildOptions(dropdownItems) {
2 return items.map(currentItem => {
3 return {
4 "label": "currentItem",
5 "value": "currentItem"
6 };
7 });
8}
Now call the loadOptions()
function in the $w.onReady()
, to load the options into the dropdown.
Replace resultsTable
with the ID of your table.
1$w.onReady(() => {
2
3 loadOptions();
4
5 $w("#resultsTable").columns = [{
6 ...
7 ...
8 ...
9
10 }];
11
12
13});
Optionally Collapse the Table on Load
- In the Properties & Events panel for the table, select Collapsed on load.
- In the code you added for the search, right below where you instructed the table to be populated with the results of the query on the data collection, add this line to expand the table.
1$w("#resultsTable").expand();
Replace resultsTable
with the ID of your table.
For example, the code for performing the search with a dropdown would look like this for a table whose index key is resultsTable
:
1 wixData.query("recipes")
2 .contains("name", $w("#searchList").value)
3 .find()
4 .then(res => {
5 $w("#resultsTable").rows = res.items;
6 $w("#resultsTable").expand();
7 });
8}
API List
- wix-data.query( ) - Creates a query.
- wix-data.WixDataQuery.find( ) - Returns the items that match a query.
- wix-data.WixDataQuery.distinct( ) - Returns the distinct items that match a query.