gregnb / mui-datatables

Datatables for React using Material-UI
MIT License
2.71k stars 934 forks source link

How can I customize filter options in MUI data grid filter #2007

Open vinitaran opened 1 year ago

vinitaran commented 1 year ago

I have a field to bookmark rows and the filter to that column is a boolean type. So the filter displays the value true or false but instead I want it to display Marked or Unmarked. How can I do that?

const columns: GridColDef[] = [ { field: "watchlist", headerName: "Wishlist", width: 120, type: "boolean", renderCell: (params) => (

handleCheckboxClick(params.row.project_id, params.value) } />
  ),
},

]

Screenshot 2023-06-22 at 09 34 05
jordan-kaxig commented 8 months ago

I solved it by using type: "singleSelect" instead of type: "boolean". For "singleSelect" types, you can define which value options you want. And also you could set the filterOperators to only hold the "is" operator.

So you would do:


import { getGridSingleSelectOperators } from "@mui/x-data-grid-pro";

const columns: GridColDef[] = [
  {
    field: "watchlist",
    headerName: "Wishlist",
    width: 120,
    type: "singleSelect",
    valueOptions: [
      { value: true, label: "Marked" },
      { value: false, label: "Unmarked" },
    ],
    filterOperators: getGridSingleSelectOperators().filter((operator) => operator.value === "is"),
    renderCell: (params) => (
      <CustomCheckbox
        rowId={params.id}
        columnId={params.field}
        checked={params.value}
        onCheckboxClick={() =>
          handleCheckboxClick(params.row.project_id, params.value)
        }
      />
    ),
  },
];
ItayTur commented 3 months ago

I did this:

export const BOOLEAN_OPTIONS = [
  {
    label: 'ENABLED',
    value: 'isTrue',
    getApplyFilterFn: () => {
      return (params) => {
        return params.value === true;
      };
    },
  },
  {
    label: 'DISABLED',
    value: 'isFalse',
    getApplyFilterFn: () => {
      return (params) => {
        return params.value === false;
      };
    },
  },

  {
    label: 'Any',
    value: 'any',
    getApplyFilterFn: () => () => true, // No filtering applied, show all rows
  },
];

and in the table columns array:

[
{
    display: 'Amount CCY',
    field: 'amountCcy',
    filterable: true,
    type: 'boolean',
    valueFormatter: ({ value }) =>
      value ? 'ENABLED' : 'DISABLED',
    filterOperators: BOOLEAN_OPTIONS,
  }
]