Articles in this section
Category / Section

How to perform searching in Date type column

3 mins read

Problem discussion:

Usually, Grid searches the records of dataSource by comparing the given search key with each record’s original value. Here, original value refers to the primitive type (date or number) of the properties. So search action cannot sort out results based on the column format. However, we can provide an alternate way to search the Grid with custom logic over the toolbar element’s event.

Solution

Intialize the template element and later assign them to the Grid toolbar.

    <div id="toolbarSearch">
        <div class="e-input-group">
            <input class="e-input" name='input' id="toolSearch" type="text" placeholder="Search" />
            <span class="e-input-group-icon e-search-icon e-icons"></span>
        </div>
    </div>
    <div id="Grid"></div>

 

import { ReturnOption, Predicate, DataManager, Query, DataUtil } from '@syncfusion/ej2-data';
import { Grid, Toolbar, Page, ColumnModel } from '@syncfusion/ej2-grids';
import { hierarchyOrderdata } from './data-source';
 
Grid.Inject(Page, Toolbar);
 
let grid: Grid = new Grid({
    dataSource: hierarchyOrderdata,
    allowPaging: true,
    toolbar: [{ template: '#toolbarSearch' }],
    load: load,
    columns: [
        { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
        { field: 'ShipCity', headerText: 'Ship City', width: 120 },
        { field: 'Freight', headerText: 'Freight', width: 120, format: 'C2' },
        { field: 'OrderDate', headerText: 'Order Date', format: { type: 'date', format: 'dd/MM/yyyy' }, width: 150 }
    ]
});
grid.appendTo('#Grid');

 

You would have noticed that the Grid has been bound with the load event. In the load event, you have to handle the search functionality for the date column and other columns separately.

let load = () => {
    // Keyup event bound to the input element 
    grid.element.addEventListener('keyup', (args: KeyboardEvent) => {
        if ((args.target as HTMLElement).getAttribute('id') === 'toolSearch' && args.key === "Enter") {
            let gridObj: Grid = grid;
            // Regex for checking date of format – “dd/MM/yyyy” 
            var regex = /^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$/;
            // Test regex with the entered value 
            let input: HTMLInputElement = (args.target as HTMLInputElement);
            if (regex.test(input.value)) {
                var count = 0;
                var predicates;
                // Value is split to form JavaScript’s Date object 
                var dateSplit = input.value.split("/");
                var dateVal = new Date(parseInt(dateSplit[2]), (parseInt(dateSplit[1]) - 1), parseInt(dateSplit[0]));
                while (count < gridObj.columns.length) {
                    // Predicate is generated for all columns with type as ‘date’
                    let col: ColumnModel = gridObj.columns[count] as ColumnModel;
                    if (col.type === "date") {
                        // Predicates are generated with the column field name and date object value 
                        predicates = (predicates === undefined) ? new Predicate(col.field, "contains", dateVal) : predicates.or(col.field, "contains", dateVal);
                    }
                    count++;
                }
                // Data manager is executed with grid’s datasource and query generated based on the predicates 
                new DataManager({ json: (gridObj.dataSource as object[]) }).executeQuery(new Query().where(predicates)).then((e: ReturnOption) => {
                    // The returned result is assigned to the grid datasource 
                    gridObj.dataSource = e.result as object[];
                });
            } else if (input.value === "") {
                if (gridObj.searchSettings.key === "") {
                    var data = hierarchyOrderdata;
                    // If the input value and search key is empty the entire data source is assigned to the grid 
                    gridObj.dataSource = DataUtil.parse.parseJson(data);
                } else {
                    // If the input value is empty but the grid contains a search key, then another search is performed with empty value to remove the search 
                    gridObj.search("");
                }
            } else {
                // Grid search method is called with the input value 
                gridObj.search(input.value);
            }
        }
    });
}

 

Output:

Grid with formatted date search results.

Figure 1: Grid with formatted date search results.

 

Grid with formatted number search results.

Figure 2: Grid with formatted number search results

TypeScript Demo: https://stackblitz.com/edit/search-grid?file=index.ts

Angular Demo: https://stackblitz.com/edit/angular-wnelll?file=app.component.ts

React Demo: https://stackblitz.com/edit/react-fyk3bx?file=index.js

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied