javascriptkendo-uitelerikkendo-gridtelerik-grid

Applying the Kendo Grid toolbar Search to the template value of a date


I have added a search toolbar to my JQuery Kendo grid. I want to use it to search dates as they appear in my grid.

The dates are c# DateTime values fetched from a Controller. I use a template to display the date in the format that I need.

The Search toolbar appears to be searching in the date format before I apply the template formatting.

Eg my date displays as 10/07/2020 but if I search for that string nothing appears. If I search for: Fri Jul 10 2020 00:00:00 GMT+0800 (W. Australia Standard Time), it will return the 10/07/2020 row.

//my grid datasource
var robotDataSource = new kendo.data.DataSource({
  transport: {
    read: {
      url: "@Url.Action("RobotList", "Robot")",
      dataType: "json",
      type: "POST"
    }
  },
  schema: {
    model: {
      fields: {
        ID: { type: 'number' },
        RobotName: { type: 'string' },
        CreatedDate: { type: 'date' }
      }
    },

  },
  pageSize: 10,
  sort: {
    field: "ID",
    dir: "desc"
  }
});
robotDataSource.fetch(function() {
});

//my grid
$("#robotGrid").kendoGrid({
  dataSource: robotDataSource,
  height: 700,
  toolbar: ["search"],
  pageable: {
    pageSizes: [10, 25, 50, 100]
  },
  sortable: true,
  filterable: true,
  columns: [
    {
      field: "ID",
      title: "ID",
      filterable: { search: true }
    }, {
      field: "RobotName",
      title: "Name",
      width: 160,
    }, {
      field: "CreatedDate",
      title: "Date Created",
      width: 160,
      template: "#=  (CreatedDate == null)? '' : kendo.toString(kendo.parseDate(CreatedDate, 'yyyy-MM-dd'), 'dd/MM/yyyy') #"
      filterable: { multi: true, search: true }
    }
  ]
});

Solution

  • Add a string formatted version of Created Date to your datasource and add a parse function like so:

    schema: {
      model: {
        fields: {
          ID: { type: 'number' },
          RobotName: { type: 'string' },
          CreatedDate: { type: 'date' },
          CreatedDateFormatted: { type: 'string' }
        }
      },
      parse: function (response) {
        for (var i = 0; i < response.length; i++) {
          response[i].CreatedDateFormatted = kendo.format("{0:dd/MM/yyyy}", response[i].CreatedDate);
        }
        return response;
      }
    },
    

    Then update your grid configuration to indicate which columns to include in the search:

    search: {
      fields: ["Id", "CreatedDateFormatted"]
    },
    

    More information is available here: https://docs.telerik.com/kendo-ui/knowledge-base/grid-filter-columns-by-date-via-search-panel