How to Add Magento 2 Admin Grid Custom Filter?

How to Add Magento 2 Admin Grid Custom Filter?

Want to find data 50% faster and report 10x easily? Magento 2 admin grid custom filter helps simplify data management in your eCommerce store.

In this tutorial, we will explore the types, features, and configuration steps of the Magento 2 admin grid custom filter.

Best Magento Hosting now

Key Takeaways

  • Custom filters enhance admin grids to meet specific business needs.

  • Follow the instructions to add custom filters to your admin grid.

  • Follow best practices for creating user-friendly custom filters.

  • Optimize custom filters for performance and scalability.

  • Improve workflow efficiency with precise filtering tailored.

What is Magento 2 Admin Grid?

Magento 2 admin grid is a powerful tool in the Magento 2 backend. It provides a tabular interface for managing and organizing data like products and orders.

The grid features filtering, sorting, and pagination for efficient data navigation. It comes with customizable columns and bulk action capabilities. These enhance productivity by offering centralized data management. It helps administrators view, edit, and process records.

Admin grids are highly extensible. They allow developers to customize grids with additional columns or actions to meet specific business needs. They simplify complex workflows, making them an essential component of the platform.

What is Magento 2 Admin Grid Custom Filter?

Magento 2 admin grid custom filter is a specialized feature that extends the default filtering capabilities of Magento 2 admin grids.

The feature allows developers to add unique filter options tailored to specific business requirements. It enables administrators to refine data display beyond the built-in filters.

Custom filters enhance data segmentation by incorporating additional attributes or fields. It simplifies the process of locating relevant records.

Admin grid custom filters simplify administration by improving data accessibility and workflow efficiency.

8 Types of Magento 2 Admin Grid Custom Filter

1. Text Filters

Text Filters

  • Text filters allow administrators to search for records based on text input. They can match full text or patterns like wildcards.

  • These are particularly useful for large datasets where specific entries need to be found quickly.

  • Developers add a text filter UI component to the grid's layout XML. Then, they write logic in the data provider for comparison.

  • You can search for a product by name and locate customers using email or first name.

2. Dropdown/Select Filters

  • Dropdown or select filters provide a predefined list of options for administrators. These filters are ideal for categorical or status-based filtering.

  • The filter is defined using a dropdown UI component. It comes with options dynamically fetched from a database or configuration.

  • You can filter products by status and sort orders by payment method.

3. Date Range Filters

  • Date range filters allow admins to filter records based on specific dates or periods. These filters utilize calendar pickers to select start and end dates.

  • Date inputs are added to the grid layout, and the backend processes records falling within the selected range.

  • You can filter orders placed within a specified date range. You can also identify customers registered during a promotional period.

4. Number Range Filters

Number Range Filters

  • These filters enable administrators to filter numeric values within a specified range. It is ideal for datasets that involve:

    1. Quantities

    2. Amounts

    3. Numerical attributes

  • Number inputs are added to the UI, and comparison logic processes the specified range.

  • You can filter products by price range and identify customers who placed more than a certain number of orders.

5. Boolean Filters

  • Description: Boolean filters are used for binary data, offering simple Yes/No or True/False filtering options.

  • Implementation: These filters often use checkboxes or toggle switches for user input.

  • Use Case Examples:

    1. Filtering products based on stock availability (In Stock/Out of Stock).

    2. Sorting customers based on subscription status.

    3. Identifying orders marked as gift-wrapped.

6. Custom Attribute Filters

  • These filters are based on custom attributes not included in Magento's default setup. They allow unique filtering tailored to a business’s specific requirements.

  • Custom attributes are added to the database. The filter logic is incorporated into the grid.

  • You can filter products by a custom "Brand" attribute and sort orders by delivery type.

7. Multi-Select Filters

Multi-Select Filters

  • Multi-select filters allow admins to choose multiple options from a list. It is ideal for scenarios where multiple criteria are applicable simultaneously.

  • The filter UI includes a multi-select component. The backend processes multiple selected values.

  • You can filter orders by multiple statuses and select products from multiple categories.

8. Relational Filters

  • Relational filters deal with data that has relationships with other entities in the Magento database.

  • These filters are more complex. They involve joining tables or querying related entities.

  • It requires modifying the grid’s data source to join and process related entity data.

  • You can filter products by their supplier name and sort orders based on the customer’s group or tier.

8 Features of Magento 2 Admin Grid Custom Filter

1. Flexible Input Types

  • Custom filters support a variety of input types, including:

    1. Text fields for partial or exact matches

    2. Dropdowns for single-select options

    3. Multi-select fields for filtering by multiple criteria

    4. Boolean toggles

    5. Date pickers for range filtering

    6. Number fields for specifying numeric ranges

  • Text filters enable you to search for customers by their email domain. Dropdown filters help segment products by status.

  • Administrators can apply the most intuitive filter type for each data field. It enhances usability and precision.

2. Advanced Filtering Logic

  • Custom filters can implement complex logic for data retrieval, such as:

    1. Greater than or less than comparisons

    2. Between ranges for dates or numbers

    3. Wildcard or regex-based searches

  • It filters orders with total amounts between $100 and $500. It also helps retrieve products whose names start with "Pro" or end with "2025."

  • It enables detailed and precise filtering, reducing the time spent manually narrowing down results.

3. Dynamic Filter Options

  • Filter options can be populated dynamically based on database entries or configurations. Dropdown or multi-select options adjust to reflect current data.

  • A dropdown for filtering orders by payment method dynamically updates when new methods are added.

  • It keeps filters up-to-date without requiring manual updates. It also ensures accurate and relevant options.

4. Integration with Grid Pagination and Sorting

Integration with Grid Pagination and Sorting

  • Custom filters integrate smoothly with the grid’s pagination and sorting functionalities. It ensures data is displayed in an organized manner.

  • Sorting filter orders by order date while maintaining page navigation. It also helps display products matching a filter across multiple pages, sorted by price or name.

  • It helps maintain usability and efficiency, especially for large datasets.

5. Customizable UI Components

  • The appearance and functionality of custom filters can be adjusted to fit specific workflows and user preferences.

  • It includes adding placeholder text to input fields for better user guidance. You can also highlight active filters with unique colors or icons.

  • It helps improve the user experience by making filters more intuitive and aligned with business workflows.

6. Modular Design

  • Filters are implemented as part of modular and reusable components. It makes them easy to maintain, extend, or integrate into other grids.

  • It involves reusing a "Brand" filter across the product grid, order grid, and inventory grid.

  • It reduces development time and simplifies the implementation of consistent filtering features.

7. Support for Relational Data

  • Custom filters can query related entities in the Magento database. It enables filtering based on relationships between data objects.

  • It enables filtering orders by the customer’s group or region. Products can be sorted by supplier or manufacturer details.

  • It helps expand filtering capabilities beyond single entities, making it more versatile.

8. Export Compatibility

  • Filters work smoothly with Magento’s export functionality. It allows filtered data to be exported in CSV or XML formats.

  • It includes exporting a list of orders filtered by date range and status. It exports customer records based on specific tiers.

  • It simplifies reporting and external data sharing, improving overall workflow.

6 Steps to Add Custom Filter in Magento 2 Admin Grid

1. Create the registration.php file at app/code/Extension/Testgrid/:

2. Create the module.xml file in app/code/Extension/Testgrid/etc/ to handle installation and updates.

3. Initialize the column in the admin grid by creating the product_listing.xml file in app/code/Extension/Testgrid/view/adminhtml/ui_component/:

4. Add a column to the grid data collection by creating AddYearlyViewsFieldToCollection.php in app/code/Extension/Testgrid/Ui/DataProvider/Product/:

5. Set up a custom filter for the column by creating AddYearlyViewsFilterToGrid.php in app/code/Extension/Testgrid/Ui/DataProvider/Product/:

6. Add strategies to include the new column and filter into the admin grid by updating the di.xml file in app/code/Extension/Testgrid/etc/adminhtml/.

Best Practices for Magento 2 Admin Grid Custom Filter

1. Follow Magento Coding Standards

  • Use Magento’s recommended coding standards and guidelines. You should adhere to the MVC and Dependency Injection principles.

  • You should also avoid hardcoding values; use Magento configuration settings whenever possible.

  • It ensures compatibility with updates and better code maintainability.

2. Use Modular and Reusable Code

  • Organize custom filters into modules to keep them isolated and reusable. You should also create separate classes or components for:

    1. Filter logic

    2. Data providers

    3. UI configurations

  • Modular code is easier to debug, extend, and reuse across multiple grids.

3. Optimize Query Performance

Optimize Query Performance

  • Write efficient SQL queries in the data provider to handle filtering logic. You should also use database indexing for fields frequently used in filters.

  • Avoid fetching unnecessary data by specifying only required columns in queries.

  • It helps prevent performance bottlenecks, especially when dealing with large datasets.

4. Leverage Magento’s UI Components

  • Use Magento’s built-in UI components like uiComponent to define filter types.

  • Customize these components only when necessary to maintain compatibility with core features.

  • It ensures alignment with Magento’s framework and reduces development effort.

5. Test Across Various Scenarios

  • Test filters with:

    1. Large datasets to evaluate performance

    2. Edge cases, such as invalid input or empty results

    3. Multiple filters are applied simultaneously

  • Use Magento's testing frameworks for unit and integration testing.

  • It ensures powerful functionality and prevents issues in production.

6. Keep Filters User-Friendly

  • Add clear labels and placeholder text for input fields. You should also use descriptive names for dropdown and multi-select options.

  • Validate user input to provide meaningful error messages for invalid entries.

  • It helps improve the admin user experience and minimizes confusion.

7. Implement Dynamic Filter Options

  • Populate dropdown and multi-select filters dynamically based on real-time data from the database or configurations.

  • Update options automatically when related data changes.

  • It keeps filters relevant and ensures administrators have accurate choices.

FAQs

1. How do I add a custom filter to the Magento 2 admin panel?

You need to create a custom admin module. Initialize the column in the UI component XML file. Add a filter to the grid using the data provider. Include functions like addFilterStrategies to refine the filtering logic.

2. How can I add a filter to the Magento 2 product grid?

You need to create a di.xml file and set up a column for the product grid. Add Magento 2 attributes in the grid layout XML. Implement protected function logic for grid filters in the data provider. It helps locate the required product quickly.

3. What is the role of the namespace and php in custom filters for Magento 2?

Using a php namespace helps create a custom filter for the Magento 2 product grid. It helps connect the table ID and supports custom logic for column filters. Paste the required code in your module to refine the grid in Magento 2 admin.

4. Can I filter customer data in the Magento admin grid?

You need to initialize the column in the UI component, create a di.xml file, and paste the following code for filter logic. It ensures the segmentation of customer data based on specific criteria. These include registration date or group.

CTA

Summary

Magento 2 admin grid custom filter enables efficient data management such as products and orders. The tutorial explores the key features of custom filters, including:

  • Enable advanced filtering options like text and date ranges for precise data retrieval.

  • Filters integrate with pagination and support real-time updates from the database.

  • Reusable components reduce development time and ensure consistent functionality.

  • Optimize queries and follow coding standards to enhance performance.

Enhance your Magento store's performance with the Magento 2 admin grid custom filter. Pair it with managed Magento hosting for unmatched speed and reliability.

Ruby Agarwal
Ruby Agarwal
Technical Writer

Ruby is an experienced technical writer sharing well-researched Magento hosting insights. She likes to combine unique technical and marketing knowledge in her content.


Get the fastest Magento Hosting! Get Started