How to dynamically build a frontend filtering UI based on the response of `archiveFilters`, such as dropdown menus or checkboxes?

Calendar 👁️ 67

Today, with the increasing richness of website content, how to enable users to quickly find the information they are interested in is a crucial operational issue.AnQiCMS (AnQiCMS) provides powerful content management capabilities, and its API interface provides a solid foundation for front-end developers to build flexible and variable interactive interfaces.Today, let's delve into how to make use ofarchiveFiltersThe response data of the interface, dynamically constructing the front-end filtering UI, such as common dropdown menus or checkboxes.

The value of the dynamic filtering interface

Imagine if your website has a large number of products, articles, or job listings, users may want to filter based on various conditions such as 'price range', 'publish time', 'city', 'education', and more.If these filter conditions are fixed, each adjustment on the backend will require front-end engineers to modify the code, which undoubtedly increases the maintenance cost.By dynamically building the filtering UI, the front-end can automatically generate the corresponding drop-down menus or checkboxes based on the real-time filtering conditions returned by the back-end interface, greatly enhancing the flexibility and maintainability of the website.

RevelationarchiveFiltersInterface: data source for filtering conditions

Of Security CMSarchiveFiltersThe interface is the core to implement this function. It allows us to get the list of filtering conditions for the specified content model.

Calling this interface is very simple, just need to send{域名地址}/api/archive/filtersSend aGETRequest and include a required parametermoduleId,moduleIdIndicates the filtering conditions under which content model you want to retrieve (such as article model, product model, etc.)

The response data structure of the interface is clear and straightforward, it usually returns an array containing multiple filter objects. Each filter object contains several key pieces of information:

  • name: This is the Chinese name that should be used for the filter on the front end, such as "City", "Education", etc., which users will see directly.
  • field_name: This is the backend field name corresponding to the filter, for examplecity/certificate. This name is very important because when the user selects the filter condition, we will transfer thisfield_nameAs a parameter name, send it together with the user's chosen valuearchiveListto get the document list that meets the conditions.
  • items: This is an array that includes all the available options of the current filter. Each option also includeslabel(The actual display text of the option, such as “Beijing”, “Bachelor”) andtotalThis indicates how many documents are under this option, although it is displayed as 0 in the example, but it can be used in actual projects according to need to display the number.

By parsing this response, we can know which filtering dimensions the current content model supports, and what specific options each dimension has.

{
  "code": 0,
  "data": [
    {
      "name": "城市",
      "field_name": "city",
      "items": [
        { "label": "全部", "total": 0 },
        { "label": "北京", "total": 0 },
        { "label": "上海", "total": 0 }
      ]
    },
    {
      "name": "学历",
      "field_name": "certificate",
      "items": [
        { "label": "全部", "total": 0 },
        { "label": "硕士", "total": 0 },
        { "label": "本科", "total": 0 }
      ]
    }
  ],
  "msg": ""
}

Practical steps for dynamically building the front-end UI.

NowarchiveFiltersThe powerful data provided, next is how to convert this data into a user-friendly filter interface on the front end.

Step 1: Obtain the filter data

Firstly, when the page loads or when the user switches the content model, we need to callarchiveFiltersThe interface retrieves the latest filtering conditions. This is usually an asynchronous operation, which can be done using JavaScript'sfetchoraxioslibraries.

async function fetchFilters(moduleId) {
  try {
    const response = await fetch(`/api/archive/filters?moduleId=${moduleId}`);
    const result = await response.json();
    if (result.code === 0) {
      return result.data; // 返回筛选器数据数组
    } else {
      console.error('获取筛选条件失败:', result.msg);
      return [];
    }
  } catch (error) {
    console.error('请求筛选条件接口出错:', error);
    return [];
  }
}

Step two: Parse and render UI components

obtaining todataAfter the array, we can iterate over this array to dynamically create front-end UI elements for each filter. For each filter object, we can use itsnameUse as the title of the filter area,field_nameWill be used as the parameter name of the backend request,itemsThe array is used to generate specific options.

Here, we can decide based on actual needs whether to use a dropdown menu (<select>) or a checkbox (<input type="checkbox">)

Create a dropdown menu (suitable for single selection filters, such as "City"):

If a user typically only selects one value for a filter dimension (such as "city"), a dropdown menu is a simple and effective choice.

function renderDropdownFilter(filterData) {
  const filterContainer = document.getElementById('filters-area'); // 假设页面上有一个ID为'filters-area'的容器
  const div = document.createElement('div');
  div.className = 'filter-group';

  const label = document.createElement('label');
  label.textContent = filterData.name + ':';
  div.appendChild(label);

  const select = document.createElement('select');
  select.setAttribute('data-field-name', filterData.field_name); // 存储field_name,方便后续获取选中的值

  filterData.items.forEach(item => {
    const option = document.createElement('option');
    option.value = item.label === '全部' ? '' : item.label; // 如果是“全部”选项,值可以设置为空字符串
    option.textContent = item.label;
    select.appendChild(option);
  });

  select.addEventListener('change', (event) => {
    // 处理用户选择的变化,触发文档列表更新
    // 例如:updateArchiveList(filterData.field_name, event.target.value);
    console.log(`选中 ${filterData.name}: ${event.target.value}`);
  });

  div.appendChild(select);
  filterContainer.appendChild(div);
}

Create a checkbox group (for multi-select filtering, such as “Tags” or certain custom attributes):

If a user may need to select multiple values for a filter dimension (such as filtering multiple 'specialties'), a group of checkboxes would be more appropriate.

`javascript function renderCheckboxFilter(filterData) { const filterContainer = document.getElementById('filters-area'); const div = document.createElement(‘div’); div.className = 'filter-group';

const label = document.createElement(‘label’); label.textContent = filterData.name + ":"; div.appendChild(label);

const checkboxGroup = document.createElement('div'); checkboxGroup.className = 'checkbox-options';

filterData.items.forEach(item => {

// 排除“全部”选项,多选框通常不需要

Related articles

Does the `archiveFilters` interface require user login authorization to access?

In the daily application of Anqi CMS, the `archiveFilters` interface is an important tool for dynamically displaying filter conditions on the front-end page. It allows the website to generate various filter options based on the field configuration of the article model, such as "city", "education", and so on.It is crucial for building a user-friendly content browsing experience, where users can quickly locate content of interest through these filtering conditions.However, many developers may have a question when integrating: does this interface require user login authorization to access?To answer this question

2025-11-09

How to properly handle the error codes returned by the `archiveFilters` interface (such as -1, 1001, 1002)?

During the operation and development of the website, we often use various API interfaces provided by Anqi CMS to dynamically obtain and display content.Among them, the `archiveFilters` interface plays an important role, helping us to obtain the document filtering conditions, thus providing users with a more refined content browsing experience.However, correctly handling the error codes returned by any API is crucial to ensure the stable operation of the website and a smooth user experience.

2025-11-09

What would the `archiveFilters` interface return if a document model does not have filterable custom fields?

In Anqi CMS, the `archiveFilters` interface is a very practical feature that allows us to retrieve the filtering conditions of specific document models, thereby helping users to implement flexible content filtering on the front-end page.For example, on a product display page, we may need to filter products based on attributes such as 'color', 'size', or 'brand'. What if a document model is exactly configured without any filterable custom fields, what will the `archiveFilters` interface return?

2025-11-09

Does the `archiveFilters` interface support retrieving filtering conditions based on a specified category ID?

When using Anqi CMS for website content management, flexibly obtaining and displaying filter conditions is a key link in improving user experience.Many friends may wonder when using the `archiveFilters` interface whether it supports retrieving filtering conditions based on specified category IDs to provide more accurate filtering options for different categories.Today, let's delve deeply into this issue.

2025-11-09

How to get the latest document list of the specified model (`moduleId`) through AnQiCMS?

In website content management, we often need to dynamically display the latest updates of a certain type of content, such as news articles, product releases, or blog updates.For websites built using AnQiCMS, leveraging its powerful API interface to obtain the latest document list under a specified model is a very basic and practical operation.This can not only help developers build dynamic pages quickly, but also provide users with timely updated information, optimizing the user experience of the website.To implement this feature, we mainly use the AnQiCMS provided

2025-11-09

What is the main difference between the `type="page"` and `type="list"` modes in the AnQiCMS document list interface?

When you are using AnQiCMS to build a website and need to retrieve document content from the backend, you will often encounter the document list interface (/api/archive/list).This interface provides a very important `type` parameter, which determines how you will obtain and process the document list data.A deep understanding of the core differences between the `type="page"` and `type="list"` modes is crucial for improving website performance, optimizing user experience, and developing more flexible features.###

2025-11-09

How to precisely control the number of documents returned and the starting offset of AnQiCMS document list (advanced usage of `limit` parameter)?

When building and managing website content, AnQiCMS provides a series of flexible API interfaces to help us accurately obtain and display data.Among them, the `archive/list` interface is the core for obtaining the document list, and its `limit` parameter demonstrates its powerful fine-grained control capabilities in terms of controlling the number of returned items and the starting offset.Understand and master the advanced usage of the `limit` parameter, which can make our website content display more flexible and efficient.### `limit` parameter basic usage

2025-11-09

How to implement descending order by publish time, view count, or update time in the AnQiCMS document list?

In website operation, how to efficiently present content lists so that users can quickly find the information they are most interested in or most valuable is an important issue.AnQiCMS provides a flexible document list feature, allowing us to easily implement content list sorting in descending order based on multiple conditions, such as publication time, page views, or update time.This not only optimizes the user experience, but also helps to improve the visibility and interaction of the content.

2025-11-09