Skip to content

Autocomplete Filter (Kraaden lib)

Ghislain B edited this page Nov 21, 2023 · 6 revisions
requires slickgrid-react >=3.0.0

Index

Demo

Demo Page | Demo Component

Introduction

AutoComplete is a functionality that let the user start typing characters and the autocomplete will try to give suggestions according to the characters entered. The collection can be a JSON files (collection of strings or objects) or can also be an external resource like a JSONP query to an external API. For a demo of what that could look like, take a look at the animated gif demo below.

Using collection or collectionAsync

If you want to pass the entire list to the AutoComplete (like a JSON file or a Web API call), you can do so using the collection or the collectionAsync (the latter will load it asynchronously). You can also see that the Editor and Filter have almost the exact same configuration (apart from the model that is obviously different).

Component
interface Props {}
interface State {
  columnDefinitions: Column[];
  gridOptions: GridOption;
  dataset: any[];
}
export class GridBasicComponent extends React.Component<Props, State> {
  componentDidMount() {
    this.defineGrid();
  }

  defineGrid(): void {
    const columnDefinitions = [
      {
        id: 'countryOfOrigin', name: 'Country of Origin', field: 'countryOfOrigin',
        formatter: Formatters.complexObject,
        dataKey: 'code', // our list of objects has the structure { code: 'CA', name: 'Canada' }, since we want to use the code`, we will set the dataKey to "code"
        labelKey: 'name', // while the displayed value is "name"
        type: FieldType.object,
        sorter: Sorters.objectString, // since we have set dataKey to "code" our output type will be a string, and so we can use this objectString, this sorter always requires the dataKey
        filterable: true,
        sortable: true,
        minWidth: 100,
        editor: {
          model: Editors.autocompleter,
          customStructure: { label: 'name', value: 'code' },
          collectionAsync: fetch('assets/data/countries.json'), // this demo will load the JSON file asynchronously
        },
        filter: {
          model: Filters.autocompleter,
          customStructure: { label: 'name', value: 'code' },
          collectionAsync: fetch('assets/data/countries.json'),
        }
      }
    ];

    const gridOptions = {/*...*/};

    this.setState((state: State) => ({
      ...state,
      gridOptions,
      columnDefinitions,
      dataset: this.getData(),
    }));
  }
}

Collection Watch

We can enable the collection watch via the column filter enableCollectionWatch flag, or if you use a collectionAsync then this will be enabled by default. The collection watch will basically watch for any changes applied to the collection (any mutation changes like push, pop, unshift, ...) and will also watch for the filter.collection array replace, when any changes happens then it will re-render the Select Filter with the updated collection list. This only applies when the collection is provided by the user.

const columnDefinitions = [
  {
    id: 'title', name: 'Title', field: 'title',
    filterable: true,
    filter: {
      collection: [ /* ... */ ],
      model: Filters.autocompleter,
      enableCollectionWatch: true,
    }
  }
];

Filter Options (AutocompleterOption interface)

All the available options that can be provided as filterOptions to your column definitions can be found under this AutocompleterOption interface and you should cast your filterOptions to that interface to make sure that you use only valid options of the jQueryUI autocomplete library.

filter: {
  model: Filters.autocompleter,
  filterOptions: {
    minLength: 3,
  } as AutocompleterOption
}

Using External Remote API

You could also use external 3rd party Web API (can be JSONP query or regular JSON). This will make a much shorter result since it will only return a small subset of what will be displayed in the AutoComplete Editor or Filter. For example, we could use GeoBytes which provide a JSONP Query API for the cities of the world, you can imagine the entire list of cities would be way too big to download locally, so this is why we use such API.

Note

I don't have time to invest in finding how to use JSONP + CORS in React, if someone wants to submit a PR (Pull Request) with the proper React code, I would be happy to merge the code and update the Wiki. For now, I'll simply make a quick and easy example with the jQuery $.ajax call just for you to get the idea of how it works.

Component
export class GridBasicComponent extends React.Component<Props, State> {
  componentDidMount() {
    this.defineGrid();
  }

  defineGrid(): void {
      // your columns definition
    const columnDefinitions = [
      {
        id: 'cityOfOrigin', name: 'City of Origin', field: 'cityOfOrigin',
        filterable: true,
        minWidth: 100,
        editor: {
          model: Editors.autocompleter,
          placeholder: 'search city', //  you can provide an optional placeholder to help your users

          // use your own autocomplete options, instead of $.ajax, use http
          // here we use $.ajax just because I'm not sure how to configure http with JSONP and CORS
          editorOptions: {
            minLength: 3, // minimum count of character that the user needs to type before it queries to the remote
            fetch: (searchText, updateCallback) => {
              $.ajax({
                url: 'http://gd.geobytes.com/AutoCompleteCity',
                dataType: 'jsonp',
                data: {
                  q: searchText // geobytes requires a query with "q" queryParam representing the chars typed (e.g.:  gd.geobytes.com/AutoCompleteCity?q=van
                },
                success: (data) => updateCallback(data)
              });
            }
          },
        },
        filter: {
          model: Filters.autocompleter,
          // placeholder: '&#128269; search city', // &#128269; is a search icon, this provide an option placeholder

          // use your own autocomplete options, instead of $.ajax, use http
          // here we use $.ajax just because I'm not sure how to configure http with JSONP and CORS
          filterOptions: {
            minLength: 3, // minimum count of character that the user needs to type before it queries to the remote
            fetch: (searchText, updateCallback) => {
              $.ajax({
                url: 'http://gd.geobytes.com/AutoCompleteCity',
                dataType: 'jsonp',
                data: {
                  q: searchText
                },
                success: (data) => {
                  updateCallback(data);
                }
              });
            }
          },
        }
      }
    ];

    const gridOptions = {/*...*/};
  }
}

Autocomplete - force user input

If you want to add the autocomplete functionality but want the user to be able to input a new option, then follow the example below:

const columnDefinitions = [
  {
    id: 'area',
    name: 'Area',
    field: 'area',
    type: FieldType.string,
    filter: {
      model: Filters.autocompleter,
      filterOptions: {
        minLength: 0,
        forceUserInput: true,
        fetch: (searchText, updateCallback) => {
          updateCallback(this.areas); // add here the array
        },
      }
    }
  },
];

You can also use the minLength to limit the autocomplete text to 0 characters or more, the default number is 3.

How to change drop container dimensions?

You might want to change the dimensions of the drop container, this 3rd party library has a customize method to deal with such a thing. Slickgrid-Universal itself is removing the width using this method, you can however override this method to change the drop container dimensions

this.columnDefinitions = [
  {
    id: 'product', name: 'Product', field: 'product', filterable: true, 
    editor: {
      model: Editors.autocompleter,
      alwaysSaveOnEnterKey: true,

      // example with a Remote API call
      editorOptions: {
        minLength: 1,
        fetch: (searchTerm, callback) => {
          // ...
        },
        customize: (_input, _inputRect, container) => {
          // change drop container dimensions
          container.style.width = '250px';
          container.style.height = '325px';
        },
      } as AutocompleterOption,
    },
];

Animated Gif Demo

Clone this wiki locally