darrachequesne / spring-data-jpa-datatables

Spring Data JPA extension to work with the great jQuery plugin DataTables (https://datatables.net/)
Apache License 2.0
440 stars 174 forks source link

Can we search date in data table? #141

Closed Vaibhav-Andhale closed 2 years ago

Vaibhav-Andhale commented 2 years ago

I have implemented server side data table in spring project but not table to search date. Please suggest changes.

darrachequesne commented 2 years ago

Yes, sure, I added an example here: https://github.com/darrachequesne/spring-data-jpa-datatables-sample

The custom specification:

    private static class FirstDaySpecification implements Specification<Employee> {
        private final LocalDate minFirstDay;
        private final LocalDate maxFirstDay;

        FirstDaySpecification(DataTablesInput input) {
            Search columnSearch = input.getColumn("firstDay").getSearch();
            String dateFilter = columnSearch.getValue();
            columnSearch.setValue("");
            if (!hasText(dateFilter)) {
                minFirstDay = maxFirstDay = null;
                return;
            }
            String[] bounds = dateFilter.split(";");
            minFirstDay = getValue(bounds, 0);
            maxFirstDay = getValue(bounds, 1);
        }

        private LocalDate getValue(String[] bounds, int index) {
            if (bounds.length > index && hasText(bounds[index])) {
                try {
                    return LocalDate.parse(bounds[index]);
                } catch (NumberFormatException e) {
                    return null;
                }
            }
            return null;
        }

        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            Expression<LocalDate> firstDay = root.get("firstDay").as(LocalDate.class);
            if (minFirstDay != null && maxFirstDay != null) {
                return criteriaBuilder.between(firstDay, minFirstDay, maxFirstDay);
            } else if (minFirstDay != null) {
                return criteriaBuilder.greaterThanOrEqualTo(firstDay, minFirstDay);
            } else if (maxFirstDay != null) {
                return criteriaBuilder.lessThanOrEqualTo(firstDay, maxFirstDay);
            } else {
                return criteriaBuilder.conjunction();
            }
        }
    }

Source: https://github.com/darrachequesne/spring-data-jpa-datatables-sample/blob/d6debb88cf75b27bbd93e67306f7adf542aa9ef4/src/main/java/sample/employee/EmployeeController.java#L125-L166

Vaibhav-Andhale commented 2 years ago

Thank you so much @darrachequesne