material-table icon indicating copy to clipboard operation
material-table copied to clipboard

Selectable Filtering options within filter row

Open calebhypes opened this issue 7 years ago • 6 comments

Is your feature request related to a problem? Please describe. I'd like to allow users to select filtering options on a per column basis.

Describe the solution you'd like Allow for the filter icon adornment to be used as a Mui <IconButton> with a Mui <Menu> if a user gives the table an option filteringSelect: true (False by default?) within the tables options property. If this option is enabled, the filter icon will be clickable and generate a menu such as the following:

Screen Shot 2019-04-09 at 1 24 35 PM

(Could use icons to clean up the text and make the menu more uniform), perhaps allowing the user to input their own filter options from the columns object.

Selecting different filters on each column would only return results from the data that meet all the criteria selected.

Describe alternatives you've considered No alternatives that cleanly meet the criteria above.

calebhypes avatar Apr 09 '19 17:04 calebhypes

I was about to open the same issue--I'm glad I searched first!

For my use case, I would love to filter with a regex pattern. I built out a little working proof-of-concept without material-table (https://mbwatson.github.io/filter/) and non-working prototype with material-table on Code Sandbox to illustrate: (https://codesandbox.io/s/materialtableadvancedfiltering-z9bek).

mbwatson avatar May 21 '19 13:05 mbwatson

@mbwatson were you able to figure this out by chance? I haven't seen any progress on this within material-table as of yet.

calebhypes avatar Jul 25 '19 17:07 calebhypes

I attempted to override the MTableFilterRow component and have made some progress but still no where near ideal or functional.

Screen Shot 2019-07-29 at 4 32 09 PM

Above you can see the replaced row with the default props I have set from the child component..

Screen Shot 2019-07-29 at 4 32 30 PM

Here you can see the drop down menu with the selectable filtering options

Screen Shot 2019-07-29 at 4 32 52 PM

Here you can see each column with different selected options for filtering (No values inputted so you can see the placeholder in place)

This is a non-functioning prototype of a custom component overriding the MTablerFilterRow

FilterComponent.js

import React from "react";
import Input from "@material-ui/core/Input";
import InputAdornment from "@material-ui/core/InputAdornment";
import FormControl from "@material-ui/core/FormControl";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import IconButton from "@material-ui/core/IconButton";
import FilterListIcon from "@material-ui/icons/FilterList";

class FilterInput extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      name: this.props.name,
      value: "",
      placeholder: "LIKE",
      filterOptions: this.props.filterOptions,
      filterOpen: false,
      anchorEl: null
    };
  }

  handleFilterClick = event => {
    this.setState({ anchorEl: event.currentTarget });
  };

  handleClose = option => {
    if (typeof option === "string") {
      this.setState({ anchorEl: null, placeholder: option });
    } else {
      this.setState({ anchorEl: null });
    }
  };

  handleChange = event => {
    this.setState({ value: event.target.value });
  };

  render() {
    return (
      <div>
        <FormControl>
          <Input
            id={this.state.name}
            type="text"
            value={this.state.value}
            onChange={this.handleChange}
            placeholder={`${this.state.placeholder} ${this.state.name}`}
            endAdornment={
              <InputAdornment position="end">
                <IconButton
                  aria-label="Select Filter"
                  onClick={this.handleFilterClick}
                >
                  <FilterListIcon onClick={this.handleFilterOpen} />
                </IconButton>
              </InputAdornment>
            }
          />
        </FormControl>
        <Menu
          id={`${this.state.name}-menu`}
          anchorEl={this.state.anchorEl}
          open={Boolean(this.state.anchorEl)}
          onClose={this.handleClose}
        >
          {this.state.filterOptions.map(option => (
            <MenuItem onClick={() => this.handleClose(option)}>
              {option}
            </MenuItem>
          ))}
        </Menu>
      </div>
    );
  }
}

export default FilterInput;

Material Table Component Override

components={{
            FilterRow: props => (
              <tr>
                <td style={{ width: "48px" }} />
                {props.columns.map(column => (
                  <td>
                    <FilterInput
                      // style={{ width: "400px" }}
                      name={column.title}
                      filterOptions={[
                        "=",
                        "!=",
                        "<",
                        ">",
                        ">=",
                        "<=",
                        "LIKE",
                        "NOT LIKE"
                      ]}
                    />
                  </td>
                ))}
              </tr>
            )
          }}

Currently working to find a way to fix the positioning of the inputs so they properly line up with the columns they represent and working to have the values input into each passed back to the parent table component to re-query the remote data for proper server side filtering/sort.

@mbrn Any chance that you'll have a solution for this built into Material Table in the near future? While I might be able to get this working with a component override, having this be a built in feature would be a simpler approach.

calebhypes avatar Jul 29 '19 20:07 calebhypes

@mbwatson were you able to figure this out by chance? I haven't seen any progress on this within material-table as of yet.

@CalebCox No, I haven't had much time to think about this, but I'm glad to see that you've been chipping away at it. I'll try to look into this again to see what I can come up with in the next few days.

mbwatson avatar Jul 29 '19 22:07 mbwatson

@mbwatson I believe I've got the bulk of this working as far as functionality is concerned.

I wrote a function called handleFilters within the component that my MaterialTable is being used in, this function is then passed down to each FilterInput component as a prop within my filter row override.

handleFilters

handleFilters = filter => {
    let array = this.state.searchParams;
    if (array.length > 0) {
      let found = array.some(el => el.paramName === filter.paramName);
      if (!found) {
        array.push(filter);
      } else {
        let index = array.findIndex(el => el.paramName === filter.paramName);
        array[index] = filter;
      }
      this.setState({ searchParams: array, needsUpdate: true });
    } else {
      this.setState({ searchParams: [filter], needsUpdate: true });
    }
  };

This function requires the parent component that is rendering the MaterialTable to have a blank array in state and a boolean which I've called needsUpdate set to false on initial render.

The function itself is called within the FilterInput components handleChange function

handleChange

  handleChange = event => {
    this.setState({ value: event.target.value });
    if (this.timeout) clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      this.props.handleFilters({
        paramName: this.props.field,
        paramValue: `${this.state.value}*`,
        inputLabel: this.props.name,
        searchOperator: this.state.placeholder,
        inputType: this.props.inputType,
        inputOrder: null
      });
    }, 500);
  };

This builds out the object my backend is expecting for search queries.

Then within the parent component containing my MaterialTable, I have the componentDidUpdate function setup as below:

componentDidUpdate()

componentDidUpdate() {
    if (this.timeout) clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      let url =
        this.state.searchParams.length > 0
          ? "URL" +
            encodeURIComponent(JSON.stringify(this.state.searchParams))
          : "URL with query string";
      if (this.state.needsUpdate) {
        this.setState({tableURL: url, needsUpdate: false});
        this.tableRef.current.onQueryChange();
      }
    }, 500);
  }

This gets called on every state update, the timeout ensures that this.state.searchParams is properly updated with the new filters for each change before making the new call, changes the URL my MaterialTable is expecting and calls the onQueryChange() function to render the table with new data that's been returned by the server-side filtering.

I've not fully tested this yet as I'm having an issue where the Input value within the TextField is being reset on re-render within my MaterialTable but when I use a standalone Material-UI table it works just fine.

calebhypes avatar Aug 07 '19 19:08 calebhypes

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. You can reopen it if it required.

stale[bot] avatar Jun 15 '20 16:06 stale[bot]