xvargr
xvargr

Reputation: 43

Primereact DataTable filtering based on column body template

Is there a way to configure a primereact datatable global filter such that it will filter based on what is displayed in the cell body (templated) instead of the raw value?

For example, I have these columns:

<Column
  field="date"
  header="Date"
  body={(row) => moment(row.date).format("DD/MM/YYYY hh:mm:ss A")}
/>

<Column
  field="completed"
  header="Completed"
  body={(row) => row.completed === "Y" ? "Completed" : "Not Completed"}
/>

row.date and row.completed are of type Date and string that I want to be displayed as a certain format.

I only want a global filter, so I have it set up and passed to the DataTable as a prop like this:

  const [filters, setFilters] = useState({
    global: {
      value: null,
      matchMode: FilterMatchMode.CONTAINS,
    },
  });
 
  ... 

  <DataTable
    filters={filters}
    globalFilterFields={myFields}
    ...
  >

  {myColumns}

  </DataTable>
  ...

The global filtering works fine, but for columns that are using templates like the date and completed column shown above, the global filter will only filter based on the raw value.

So a row will be matched if I type in "Y" for the completed column, but not "Completed", and it will only match the string representation of the Date object as in "Thu Feb 08 2024 ..." but not "08/02/2024".

I can not pass in the data to the DataTable pre-formatted as it will mess up the sorting, like for dates, which will then be compared as strings. I also know of the filterFunction Column prop, but it is not well explained in the docs, and I think it not used when using global filters as my logs did not fire when I tried it.

Is there any way for me to filter these columns based on the templated values or maybe a different approach to this problem?

Upvotes: 1

Views: 788

Answers (2)

vishal bhuva
vishal bhuva

Reputation: 7

Please convert your date column to a string, like your key date. Your array is item.date

<DataTable
          value={item.task.map((item)=>return {...item,date:JSON.stringify(moment(item.date).format("DD/MM/YYYY hh:mm:ss A"))})}
          filters={filters}
          onFilter={onFilter}
          filterDisplay="row"
          lazy
>
  <Column field="col1" filter={true} />
  <Column field="col2" filter={true} />
  <Column field="col3" filter={true} />
</DataTable>
);

Upvotes: -1

Lovis
Lovis

Reputation: 1

In my case, I created a new column with the string value, and after you can search your global filters

Upvotes: 0

Related Questions