/how-to-build-lovable

How to build Search filtering and sorting with Lovable?

Discover how to build advanced search filtering and sorting with Lovable. Follow our step-by-step guide to create efficient, user-friendly web experiences.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to build Search filtering and sorting with Lovable?

 
Setting Up Your Lovable Project
 

  • Create a new Lovable project (using your browser-based editor in Lovable).
  • Add a new file named index.html that will serve as the main entry point of your app.
  • Add another new file called searchSort.js where all the search, filtering, and sorting logic will reside.

 
Adding Dependencies
 

  • Lovable does not provide a terminal, so you need to add any dependency via code. In the index.html file, include the Lovable built-in library for search filtering and sorting. Insert the following snippet inside the <head> section:

<!-- Add Lovable search and sorting library from CDN -->
<script src="https://cdn.lovable.com/libs/lovable-sort-filter.min.js"></script>
  • This library will provide utility functions to help with filtering and sorting; adjust the URL if your version differs.

 
Implementing Search Functionality
 

  • In your index.html, add an input field where users can type in their search queries. Insert this code within the <body> section before your main content:

<!-- Search Input Field -->
<input type="text" id="searchInput" placeholder="Search items..." />
  • In the searchSort.js file, add an event listener for the input field that will capture the user input and filter the items accordingly. Insert the following code at the top of the file:

// Wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
  const searchInput = document.getElementById('searchInput');
  const items = document.querySelectorAll('.item'); // items to be filtered

  // Listen for keystrokes in the search input field
  searchInput.addEventListener('input', function() {
    const query = this.value.toLowerCase();

    items.forEach(function(item) {
      // Compare the item text content with the query
      if(item.textContent.toLowerCase().includes(query)) {
        item.style.display = '';
      } else {
        item.style.display = 'none';
      }
    });
  });
});

 
Implementing Filtering Functionality
 

  • Add a dropdown filter control in your index.html file. Place the following snippet below the search input:

<!-- Filter Dropdown Control -->
<select id="filterSelect">
  <option value="all">All Categories</option>
  <option value="category1">Category 1</option>
  <option value="category2">Category 2</option>
</select>
  • In the searchSort.js file, add code to listen for changes on the filter control. Assume that each item has a data attribute data-category to indicate its category. Append this code right after the search functionality code:

document.addEventListener('DOMContentLoaded', function() {
  // Existing search code here...

  const filterSelect = document.getElementById('filterSelect');

  // Listen for changes in filter dropdown
  filterSelect.addEventListener('change', function() {
    const selectedCategory = this.value;

    items.forEach(function(item) {
      const itemCategory = item.getAttribute('data-category');

      if(selectedCategory === 'all' || itemCategory === selectedCategory) {
        item.style.display = '';
      } else {
        item.style.display = 'none';
      }
    });
  });
});

 
Implementing Sorting Functionality
 

  • Add sorting controls to your index.html. For example, create buttons that allow sorting by name or date. Place this code below the filtering dropdown:

<!-- Sorting Buttons -->
<button id="sortByName">Sort by Name</button>
<button id="sortByDate">Sort by Date</button>
  • In the searchSort.js file, write functions to sort the list of items. Append the following code to implement sorting functionality:

document.addEventListener('DOMContentLoaded', function() {
  // Existing search and filter code here...

  const sortByNameBtn = document.getElementById('sortByName');
  const sortByDateBtn = document.getElementById('sortByDate');
  const container = document.getElementById('itemsContainer'); // container element holding all items

  // Function to sort items by name
  function sortByName() {
    // Convert NodeList into array for sorting
    const itemsArray = Array.from(items);
    itemsArray.sort(function(a, b) {
      return a.textContent.localeCompare(b.textContent);
    });

    // Append sorted items
    itemsArray.forEach(function(item) {
      container.appendChild(item);
    });
  }

  // Function to sort items by date (assumes each item has a data-date attribute)
  function sortByDate() {
    const itemsArray = Array.from(items);
    itemsArray.sort(function(a, b) {
      return new Date(a.getAttribute('data-date')) - new Date(b.getAttribute('data-date'));
    });

    itemsArray.forEach(function(item) {
      container.appendChild(item);
    });
  }

  sortByNameBtn.addEventListener('click', sortByName);
  sortByDateBtn.addEventListener('click', sortByDate);
});
  • Ensure that your HTML items (for example, div elements representing records) are inside a container with the id itemsContainer and include the proper data attributes (data-category and data-date):

<div id="itemsContainer">
  <div class="item" data-category="category1" data-date="2023-09-01">Item A</div>
  <div class="item" data-category="category2" data-date="2023-08-15">Item B</div>
  <div class="item" data-category="category1" data-date="2023-07-20">Item C</div>
</div>

 
Integrating Everything in Lovable
 

  • In the index.html file, include your searchSort.js script at the end of the <body> section by adding the following code snippet:

<!-- Include JavaScript for search, filtering, and sorting -->
<script src="searchSort.js"></script>
  • Make sure all the files (index.html and searchSort.js) are saved and that your Lovable project references each correctly.

 
Testing and Fine-Tuning the Application
 

  • Use the Lovable live preview feature to test your changes. When the page loads, the search input, filter dropdown, and sorting buttons should interact with the items.
  • Type into the search input to see items filter in real time based on their names.
  • Select different categories from the dropdown to filter items.
  • Click the sort buttons to rearrange the items by name or by date.
  • If the functionality does not work as expected, review your code for typos and ensure that all the correct element IDs and data attributes are applied.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

How to Build Search, Filtering, and Sorting with Lovable Using Express and MongoDB


const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function connectDB() {
  await client.connect();
  return client.db('lovableDB');
}

app.get('/api/lovables', async (req, res) => {
  const { search, category, sortBy, order } = req.query;
  const db = await connectDB();
  let query = {};
  
  if (search) {
    query.$or = [
      { title: { $regex: search, $options: 'i' } },
      { content: { $regex: search, $options: 'i' } }
    ];
  }
  
  if (category) {
    query.category = category;
  }
  
  let sortOptions = {};
  if (sortBy) {
    sortOptions[sortBy] = (order && order.toLowerCase() === 'desc') ? -1 : 1;
  }
  
  try {
    const items = await db.collection('lovables')
      .find(query)
      .sort(sortOptions)
      .toArray();
    res.json({ success: true, data: items });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

How to Build Search Filtering and Sorting for Lovable Items Using Express and Axios


const express = require('express');
const axios = require('axios');

const app = express();

app.get('/api/lovables/external', async (req, res) => {
  const { search, category, sortBy, order } = req.query;

  try {
    // Fetch data from an external API that provides base "lovable" items
    const response = await axios.get('https://api.external-service.com/lovables', {
      params: { category }
    });
    let items = response.data.items;

    // Search filtering using case-insensitive matching on title and description
    if (search) {
      const searchLower = search.toLowerCase();
      items = items.filter(item => {
        return (item.title && item.title.toLowerCase().includes(searchLower)) ||
               (item.description && item.description.toLowerCase().includes(searchLower));
      });
    }

    // Sorting logic based on sortBy and order parameters
    if (sortBy) {
      items.sort((a, b) => {
        if (a[sortBy] < b[sortBy]) return order === 'desc' ? 1 : -1;
        if (a[sortBy] > b[sortBy]) return order === 'desc' ? -1 : 1;
        return 0;
      });
    }

    res.json({ success: true, data: items });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

app.listen(4000, () => {
  console.log('Server running on port 4000');
});

How to build search filtering and sorting for Lovable using Node.js and Sequelize


const express = require('express');
const { Sequelize, DataTypes, Op } = require('sequelize');

const app = express();
const sequelize = new Sequelize('postgres://user:password@localhost:5432/lovableDB');

const Lovable = sequelize.define('Lovable', {
  title: { type: DataTypes.STRING },
  description: { type: DataTypes.TEXT },
  category: { type: DataTypes.STRING },
  rating: { type: DataTypes.FLOAT }
}, {
  tableName: 'lovables',
  timestamps: false
});

app.get('/api/lovables/search', async (req, res) => {
  const { search, category, sortBy = 'rating', order = 'asc', minRating } = req.query;
  const where = {};

  if (search) {
    where[Op.or] = [
      { title: { [Op.iLike]: `%${search}%` } },
      { description: { [Op.iLike]: `%${search}%` } }
    ];
  }
  if (category) {
    where.category = category;
  }
  if (minRating) {
    where.rating = { [Op.gte]: parseFloat(minRating) };
  }

  try {
    const results = await Lovable.findAll({
      where,
      order: [[sortBy, order.toUpperCase()]]
    });
    res.json({ success: true, data: results });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

sequelize.authenticate().then(() => {
  app.listen(5000, () => {
    console.log('Server running on port 5000');
  });
}).catch(err => {
  console.error('Database connection error:', err);
});

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Best Practices for Building a Search filtering and sorting with AI Code Generators

 
Introduction
 

This guide explains best practices for building search filtering and sorting functionalities using AI code generators. The goal is to assist non-technical people in understanding how to leverage these tools to generate clean, efficient code that meets your application’s needs.

 
Prerequisites
 

  • A basic understanding of how search, filtering, and sorting logic work.
  • Access to an AI code generator tool, such as Copilot, ChatGPT, or similar platforms.
  • Familiarity with your development environment and the programming language you intend to use.

 
Planning Your Search, Filtering, and Sorting Features
 

  • Determine the data source. Understand where your data comes from (e.g., databases, APIs, or static files).
  • Identify the fields to be searched, filtered, and sorted. This may include names, dates, categories, etc.
  • Outline the user experience. Consider how users will interact with these features (search bar, filter checkboxes, sort dropdowns).

 
Setting Up Your Project Environment
 

  • Create a new project folder for your application using your preferred IDE or code editor.
  • Install necessary dependencies. For example, if using Python, you might need packages like Flask for a web application or Pandas for data manipulation.
  • Document the basic structure of your project to keep track of where the search, filtering, and sorting functionalities will be implemented.

 
Integrating AI Code Generators
 

  • Use your AI code generator to create boilerplate code for search functionalities. Ask it to generate functions based on your requirements.
  • Verify and test the generated code. AI tools can provide a starting point, but manual review ensures that the code is efficient and meets your criteria.
  • Incorporate inline comments in the generated code to explain the logic, making future modifications simpler.

 
Implementing Search Filtering Functionality
 

  • Develop a search function that takes a user query and a dataset as inputs. For example, you can start with a simple function:

def search\_items(query, data):
    # Convert the query to lowercase for case-insensitive search
    query = query.lower()
    # Return items where the query is found in item text
    return [item for item in data if query in item.lower()]
  • Test the search functionality with different queries to ensure accuracy and consistency.

 
Implementing Filtering and Sorting
 

  • Create filtering logic based on specific criteria such as category or date. AI code generators can help produce the structure for such functions.
  • Develop a sorting function to order items based on a key attribute. For instance:

def sort\_items(items, key='name', reverse=False):
    # Sort items by the specified key
    return sorted(items, key=lambda x: x[key], reverse=reverse)
  • Chain filtering and sorting functions. First filter the dataset according to user criteria, then sort the resulting items.
  • Ensure that your functions are modular so that individual parts can be tested independently.

 
Testing and Debugging
 

  • Use small test datasets to run through your search, filtering, and sorting functions. This helps you validate correct outputs.
  • Employ print statements or logging to track data flow and catch unexpected behavior during execution.
  • Refine your AI-generated code by comparing the expected behavior with the actual results.
  • Consider writing simple unit tests for each function to streamline future debugging efforts.

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022