top of page

A Deep Dive Into Custom Filters with Wix Velo

Updated: Oct 13, 2023


blog graphic title

Introduction:

Wix Velo is a powerful development platform that allows you to extend the capabilities of your Wix site through coding. One of the most sought-after customizations is the ability to implement a custom search feature with keywords and filters. In this blog post, we will take a deep dive into integrating this feature using Wix Velo.


Step 1: Create a Database

  1. Access the Database: Navigate to your Wix Editor, click on the 'Content Manager' from the left toolbar, and select 'Database'.

  2. Create a New Collection: Click on '+ New Collection' and name your collection. Populate your database with relevant fields and information that you wish to be searchable. For example, if you are making an e-commerce site, you may have fields like product name, category, price, and description.


Step 2: Add User Input Elements

  1. Add a Search Box: From the left toolbar, click 'Add' and select 'User Input'. Drag a text input box to where you want your search bar to be. Name it something like 'searchInput'.

  2. Add a Filter Dropdown: In the same way, add a dropdown box for filters, such as categories or price ranges. Populate it with the filter options you want. Name it something descriptive, like 'filterDropdown'.

  3. Add a Search Button: Additionally, add a button that users will click to perform the search. Name it 'searchButton'.


Step 3: Add a Repeater

  1. Choose a Repeater: From the left toolbar, click 'Add', then 'List', and choose a 'Repeater'. Customize the design to match your site aesthetics.

  2. Populate Repeater: Add text elements, images, or other items to your repeater that will display the search results. Bind them to the relevant fields in your database.


Step 4: Write Code

  1. Access Code Panel: At the bottom of your editor, you’ll see the code panel. This is where you’ll write your JavaScript code.

  2. Write the Code: Let's break down the process by starting with just the search functionality using keywords from an input box. In this example, users will type keywords into an input box, and when they click the search button, the page will display results that match those keywords.



Search Functionality



import wixData from 'wix-data';  

$w.onReady(function () {  

// Event listener for the search button     
$w("#searchButton").onClick(() => {          

        // Get the keyword from the input box
        const keyword = $w("#searchInput").value;          
       
        // Build the query
        let query = wixData.query('YourCollectionName')                                          .contains('searchField', keyword);          

        // Execute the query         
        query.find().then(results => {              

// Display the results in a repeater             
$w("#repeater").data = results.items;         
        });     
    }); 
}); 

Explanation:

  1. Event Listener for Search Button: Listens for the click event on the search button (#searchButton). When the button is clicked, the code inside the function will execute.

  2. Get Keyword from Input Box: Retrieves the text entered by the user in the input box (#searchInput) and stores it in the constant keyword.

  3. Build the Query: Initializes a new query on your database collection. You must replace YourCollectionName with the name of your collection. The .contains method searches within the field searchField (replace this with the name of the field you want to search) for any entries that contain the keyword.

  4. Execute the Query: The .find() method performs the search with the query you built. Once it's done, it returns a Promise, and the .then() method is used to handle the results. Inside, you're setting the data of the repeater element to be the items returned by the search. Replace #repeater with the name you gave your repeater element.

  5. Display the Results: The results of the query are displayed using a repeater. A repeater is a Wix element that allows you to display a list of items that are based on a template you design.

Please ensure that you've named the relevant elements to your Wix page (input box named 'searchInput', button named 'searchButton', and repeater named 'repeater') and that you replace the placeholders (YourCollectionName and searchField) with the appropriate names from your collection.

Dropdown Filter


Let's add another step to the code which involves using a dropdown filter. This allows users to not only search by keywords but also to narrow down their search based on a selected category from a dropdown menu.

import wixData from 'wix-data';

$w.onReady(function () {

    // Event listener for the search button
    $w("#searchButton").onClick(() => {

        // Get the keyword from the input box
        const keyword = $w("#searchInput").value;

        // Get the selected category from the dropdown
        const selectedCategory = $w("#categoryDropdown").value;

        // Build the query
        let query = wixData.query('YourCollectionName')
                           .contains('searchField', keyword);

        // If a category is selected, add it to the query
        if (selectedCategory) {
            query = query.eq('categoryField', selectedCategory);
        }

        // Execute the query
        query.find().then(results => {

            // Display the results in a repeater
            $w("#repeater").data = results.items;
        });
    });
});

Explanation:

  1. Get Selected Category from Dropdown: This line grabs the value selected in the category dropdown. #categoryDropdown should match the name you gave your dropdown element.

  2. Add Category to Query: The if-statement checks if a category has been selected from the dropdown. If so, it modifies the query to only include items that match the selected category using the .eq() method. Replace [categoryField ] with the field in your database that you want to filter by.

Make sure you have added a dropdown element to your Wix page and named it 'categoryDropdown'. Also, populate the dropdown with the categories you want users to be able to select. Ensure that you replace placeholders like 'YourCollectionName', 'searchField', and 'categoryField' with the appropriate names from your collection. This code allows users to perform a search with keywords and to filter the results by selecting a category from the dropdown.

Min-Max Filter


Now let's add an additional step to filter results using a minimum and maximum range, for instance, filtering products by price range. We will use two input elements to get the min and max values and modify the query accordingly.

Here's the updated code with the additional min-max filter step:

import wixData from 'wix-data';

$w.onReady(function () {

    // Event listener for the search button
    $w("#searchButton").onClick(() => {

        // Get the keyword from the input box
        const keyword = $w("#searchInput").value;

        // Get the selected category from the dropdown
        const selectedCategory = $w("#categoryDropdown").value;

        // Get the minimum value from the min input box
        const minValue = $w("#minValueInput").value;

        // Get the maximum value from the max input box
        const maxValue = $w("#maxValueInput").value;

        // Build the query
        let query = wixData.query('YourCollectionName')
                           .contains('searchField', keyword);

        // If a category is selected, add it to the query
        if (selectedCategory) {
            query = query.eq('categoryField', selectedCategory);
        }

        // If min and max values are provided, add them to the        //query
        if (minValue && maxValue) {
            query = query.between('priceField', Number(minValue), Number(maxValue));
        }

        // Execute the query
        query.find().then(results => {

            // Display the results in a repeater
            $w("#repeater").data = results.items;
        });
    });
});

Explanation:


This step includes two sub-steps:


1. Retrieve the minimum and maximum values entered by the user in the input boxes (#minValueInput and #maxValueInput) and store them in the constants minValue and maxValue.

const minValue = $w("#minValueInput").value;
const maxValue = $w("#maxValueInput").value;

2.a If both minimum and maximum values are provided, modify the query to filter results within this range using the .between() method. Replace priceField with the field in your database you want to filter by (e.g., price).

if (minValue && maxValue) {
    query = query.between('priceField', Number(minValue), Number(maxValue));
}

Make sure you have added two input elements to your Wix page and named them minValueInput and maxValueInput for users to input minimum and maximum values respectively.



2.b If only one of the minimum or maximum values is provided, we can modify the query to filter accordingly. If only the minimum value is provided, we can filter the results to show items greater than or equal to this value. Similarly, if only the maximum value is provided, we can filter results to show items less than or equal to this value.


Here's the updated portion of the code that handles min-max filtering:

// If min and max values are provided, add them to the query
if (minValue && maxValue) {
    query = query.between('priceField', Number(minValue), Number(maxValue));
} else if (minValue) {
    query = query.ge('priceField', Number(minValue));
} else if (maxValue) {
    query = query.le('priceField', Number(maxValue));
}

Explanation of the modified step:

  • If both minimum and maximum values are provided, the .between() method is used to filter results within this range.

  • If only the minimum value is provided, the .ge() method (greater than or equal to) is used to filter results greater than or equal to the minimum value.

  • If only the maximum value is provided, the .le() method (less than or equal to) is used to filter results less than or equal to the maximum value.

This addition makes the filtering more flexible, allowing users to filter results even if they only provide one of the minimum or maximum values.


Date Range Filter


Once again, let's add an additional step to filter results, but now, using a date range. We'll use two date pickers so that users can choose the start and end dates to filter content within the selected date range. Here's how the code would be modified to include this date range filter:

import wixData from 'wix-data';

$w.onReady(function () {

    // Event listener for the search button
    $w("#searchButton").onClick(() => {

        // Get the keyword from the input box
        const keyword = $w("#searchInput").value;

        // Get the selected category from the dropdown
        const selectedCategory = $w("#categoryDropdown").value;

        // Get the minimum value from the min input box
        const minValue = $w("#minValueInput").value;

        // Get the maximum value from the max input box
        const maxValue = $w("#maxValueInput").value;

        // Get the start date from the start date picker
        const startDate = $w("#startDatePicker").value;

        // Get the end date from the end date picker
        const endDate = $w("#endDatePicker").value;

        // Build the query
        let query = wixData.query('YourCollectionName')
                           .contains('searchField', keyword);

        // If a category is selected, add it to the query
        if (selectedCategory) {
            query = query.eq('categoryField', selectedCategory);
        }

        // If min and max values are provided, add them to the //query
        if (minValue && maxValue) {
            query = query.between('priceField', Number(minValue), Number(maxValue));
        } else if (minValue) {
            query = query.ge('priceField', Number(minValue));
        } else if (maxValue) {
            query = query.le('priceField', Number(maxValue));
        }

        // If start and end dates are provided, add them to the //query
        if (startDate && endDate) {
            query = query.between('dateField', new Date(startDate), new Date(endDate));
        }

        // Execute the query
        query.find().then(results => {

            // Display the results in a repeater
            $w("#repeater").data = results.items;
        });
    });
});

Explanation


1. Retrieve the start and end dates selected by the user in the date pickers (#startDatePicker and #endDatePicker) and store them in the constants startDate and endDate.

const startDate = $w("#startDatePicker").value;
const endDate = $w("#endDatePicker").value;

2.a If both start and end dates are selected, modify the query to filter results within this date range using the .between() method. Replace dateField with the field in your database that contains the date information you want to filter by.

if (startDate && endDate) {
    query = query.between('dateField', new Date(startDate), new Date(endDate));
}

Make sure you have added two date picker elements to your Wix page and named them startDatePicker and endDatePicker for users to select the start and end dates respectively. This code allows users to filter results within a specified date range. 2.b If only the start date is provided, we can filter the results to show items on or after this date. Similarly, if only the end date is provided, we can filter results to show items on or before this date.

Here's the updated portion of the code that handles the date range filtering:

// If start and end dates are provided, add them to the query
if (startDate && endDate) {
    query = query.between('dateField', new Date(startDate), 
    new Date(endDate));
} else if (startDate) {
    query = query.ge('dateField', new Date(startDate));
} else if (endDate) {
    query = query.le('dateField', new Date(endDate));
}

Explanation of the modified step:

  • If both start and end dates are provided, the .between() method is used to filter results within this date range.

  • If only the start date is provided, the .ge() method (greater than or equal to) is used to filter results on or after the start date.

  • If only the end date is provided, the .le() method (less than or equal to) is used to filter results on or before the end date.

This addition ensures that users can filter results even if they only provide one of the start or end dates. This makes the date range filtering more flexible and user-friendly.

Step 5: Combine Multiple Filters.

In the previous code snippets, the filters were constructed to work independently. To have them work together, you'll need to progressively build the query based on the filters that are set by the user. Here's how the code could be structured to have all filters work in conjunction:

import wixData from 'wix-data';

$w.onReady(function () {

    // Event listener for the search button
    $w("#searchButton").onClick(() => {

        // Start by initializing the query for your collection
        let query = wixData.query('YourCollectionName');

        // Keyword Filter
        const keyword = $w("#searchInput").value;
        if (keyword) {
            query = query.contains('searchField', keyword);
        }

        // Category Filter
        const selectedCategory = $w("#categoryDropdown").value;
        if (selectedCategory) {
            query = query.eq('categoryField', selectedCategory);
        }

        // Price Range Filter
        const minValue = $w("#minValueInput").value;
        const maxValue = $w("#maxValueInput").value;
        
        if (minValue && maxValue) {
            query = query.between('priceField', Number(minValue), Number(maxValue));
        } else if (minValue) {
            query = query.ge('priceField', Number(minValue));
        } else if (maxValue) {
            query = query.le('priceField', Number(maxValue));
        }

        // Date Range Filter
        const startDate = $w("#startDatePicker").value;
        const endDate = $w("#endDatePicker").value;
        
        if (startDate && endDate) {
            query = query.between('dateField', new Date(startDate), new Date(endDate));
        } else if (startDate) {
            query = query.ge('dateField', new Date(startDate));
        } else if (endDate) {
            query = query.le('dateField', new Date(endDate));
        }

        // Execute the query
        query.find().then(results => {

            // Display the results in a repeater
            $w("#repeater").data = results.items;
        });
    });
});

This code initializes a base query and progressively adds conditions to it based on which filters the user has set. It then executes the query once all the filters have been added. This way, users can use a single filter, or any combination of filters together, to narrow down the results according to their preferences.


Conclusion

In this tutorial, we have successfully integrated a custom search functionality with various filters, including keyword search, category selection, price range, and date range filtering, using Wix Velo. This combination of filters enhances the user experience, allowing visitors to find the content they are looking for more efficiently and effectively.


As a business or content creator, fine-tuning the search and filter functionality is crucial. The versatility of filters accommodates different user preferences, ensuring that they find what they need with minimal effort. It's also essential to keep monitoring user behavior to understand which filters are used the most and continuously improve the features based on user feedback.


If you find yourself needing more advanced features or want to ensure that your website's search functionality is top-notch, consider seeking professional help.


Are you looking for expert assistance to enhance your website's capabilities? CodeMasters Agency is here for you! Our team of dedicated developers and designers specialize in creating bespoke web solutions tailored to your needs. From implementing advanced search features to optimizing your website for performance and user experience, CodeMasters Agency has got you covered. Get in touch with us today and take your website to the next level!



bottom of page