primeng icon indicating copy to clipboard operation
primeng copied to clipboard

Datatable filter is not working with LazyLoad datatable

Open rpeleias-v1 opened this issue 10 years ago • 18 comments

My custom datatable filter is not working when I enable lazy loading. When I write a text to filter my datatable, my onLazyLoad() event has been called and loading all rows

My html below:

<div [layoutbox]="'column'">
			<div [layoutbox]="'field'">
				<input #filtroPrincipioAtivo type="text" pInputText style="float:left" placeholder="Pesquise pelo princípio ativo desejado">
			</div>
		</div>

<p-dataTable [value]="principiosAtivos" [rows]="5" [paginator]="true" [pageLinks]="5" [responsive]="true" [stacked]="stacked"
			[lazy]="false" selectionMode="single" [(selection)]="selectedPrincipioAtivo" [globalFilter]="filtroPrincipioAtivo" [paginator]="true"
			[totalRecords]="totalResultados" (onLazyLoad)="loadLazy($event)">
			<p-column field="id" header="Id" [sortable]="true" styleClass="column-id-size"></p-column>
			<p-column field="nome" header="Nome" [sortable]="true"></p-column>
		</p-dataTable>

My component.ts file below:

loadLazy(event: LazyLoadEvent) {
       this.primeiroRegistro = event.first;
       this.listar(this.primeiroRegistro, this.totalResultadosPorPagina);       
    }

rpeleias-v1 avatar Nov 17 '16 16:11 rpeleias-v1

@cagataycivici I have to confirm this bug, so features like filter and sort not working with [lazy]="true"

reza-ebrahimi avatar Dec 02 '16 20:12 reza-ebrahimi

@reza-ebrahimi But this bug will be repaired?

Or are there functions that definitely do not work with lazy load?

If there are some functions that do not work with lazy load could they tell if there is more?

ahelord avatar Jan 16 '17 20:01 ahelord

Hello people, this was the only discussion i could find about this topic. So let me bother you guys a little.

What were the conclusions about using Lazy Load and Filter toghether? I'm trying to get them to work here but it's just not happening.

The atribute filters of the event LazyLoadEvent is always missing, even tough i defined the filter parameters in the datatable.

acrackintheice avatar Jan 28 '17 06:01 acrackintheice

Hi there, any solution of this problem. I am facing the same issue primeng datatable filter is not working with lazy loading.

waqar-ali avatar May 21 '17 14:05 waqar-ali

Provide a plunkr please.

cagataycivici avatar May 21 '17 14:05 cagataycivici

Here is the plunkr https://plnkr.co/edit/jDCOo8kwhOfOTyJw6H4m?p=preview

Filter is not working with lazy loading option to true, when you set the [lazy]="false", filters works fine.

waqar-ali avatar May 21 '17 15:05 waqar-ali

Using plnkr for lazy loading could be tricky. I would suggest to use plunkr for lazy loading testing to display LazyLoadEvent JSON content, not to rely on data table content. The data could be any and it is not relevant what is actually is shown in data table because LazyLoadEvent content is the most important.

gorokhmn avatar May 23 '17 13:05 gorokhmn

Filter is not working for me either when [lazy]="true". Any solution to this problem? Thanks.

alubhaji avatar Jun 01 '17 13:06 alubhaji

Hi,

I am not sure my solution is robust to any case but it is working for me. Any comment to improve it is welcome.

<p-dataTable #dt
             [value]="displayedRows"
             [editable]="true"
             [sortField]="startDate" [sortOrder]="1" [sortMode]="multiple"
             filterDelay="500"
             [lazy]="lazy" rows="10" [paginator]="lazy"
             pageLinks="20" [rowsPerPageOptions]="rowsPerPageOptions"
             [totalRecords]="totalRowsNb" (onLazyLoad)="loadLazy($event)">

// ************ Lazy load & filters & sorts
  loadLazy(event: LazyLoadEvent) {
    // filter data
    this.filteredRows = this.allRows.filter(row => this.filterField(row, event.filters))
    // sort data
    this.filteredRows.sort((a, b) => this.compareField(a, b, event.sortField) * event.sortOrder);
    this.displayedRows = this.filteredRows.slice(event.first, (event.first + event.rows))
    this.totalRowsNb = this.filteredRows.length;
  }

  filterField(row, filter) {
    let isInFilter = false;
    let noFilter = true;

    for (var columnName in filter) {
      if (row[columnName] == null) {
        return;
      }
      noFilter = false;
      let rowValue: String = row[columnName].toString().toLowerCase();
      let filterMatchMode: String = filter[columnName].matchMode;
      if (filterMatchMode.includes("contains") && rowValue.includes(filter[columnName].value.toLowerCase())) {
        isInFilter = true;
      } else if (filterMatchMode.includes("startsWith") && rowValue.startsWith(filter[columnName].value.toLowerCase())) {
        isInFilter = true;
      } else if (filterMatchMode.includes("in") && filter[columnName].value.includes(rowValue)) {
        isInFilter = true;
      }
    }

    if (noFilter) { isInFilter = true; }

    return isInFilter;
  }

  compareField(rowA, rowB, field: string): number {
    if (rowA[field] == null) return 1; // on considère les éléments null les plus petits
    if (typeof rowA[field] === 'string') {
      return rowA[field].localeCompare(rowB[field]);
    }
    if (typeof rowA[field] === 'number') {
      if (rowA[field] > rowB[field]) return 1;
      else return -1;
    }
  }

pectum83 avatar Jun 01 '17 14:06 pectum83

I can't replicate it, I'm not sure if it is clear that in lazy mode, the loading should be done by your backend, DataTable does not do page-sort-filter in lazy mode, it just sends metadata in LazyLoadEvent so that you can do a backend call to load the lazy data everytime filter-sort-page happens.

cagataycivici avatar Jun 12 '17 11:06 cagataycivici

Adding onto @robopec 's comment, adding a final else statement and returning false will cause the column filter logic to be ANDed together. Depending on how you want the filter logic

filterField(row, filter) {
    let isInFilter = false;
    let noFilter = true;

    for (var columnName in filter) {
      if (row[columnName] == null) {
        return;
      }
      noFilter = false;
      let rowValue: String = row[columnName].toString().toLowerCase();
      let filterMatchMode: String = filter[columnName].matchMode;
      if (filterMatchMode.includes("contains") && rowValue.includes(filter[columnName].value.toLowerCase())) {
        isInFilter = true;
      } else if (filterMatchMode.includes("startsWith") && rowValue.startsWith(filter[columnName].value.toLowerCase())) {
        isInFilter = true;
      } else if (filterMatchMode.includes("in") && filter[columnName].value.includes(rowValue)) {
        isInFilter = true;
      }
      else
        return false;
    }

    if (noFilter) { isInFilter = true; }

    return isInFilter;
  }

coshea avatar Aug 03 '17 14:08 coshea

Thanks @robopec, it works!

jliean avatar Aug 19 '17 21:08 jliean

Me too facing same problem. robopec solution worked for me . this solution only for column filter not for global filter.

Please any one help for global filter with lazy load??

Manunarasingh avatar Nov 03 '17 12:11 Manunarasingh

@Manunarasingh Maybe you can try: filterGlobal(row, value) { for(let i=0; i<this.columns.length; i++) { let column: Column = this.columns[i]; if(row[column.name] == null) { continue; } let rowValue: String = row[column.name].toString().toLowerCase(); if(rowValue.includes(value.toLowerCase()) { return true; } } return false; }

loadLazy(event: LazyLoadEvent) { this.loading = true; this.filteredRows = this.dataSource.filter(row => this.filterField(row, event.filters)); if(event.globalFilter.trim()) { this.filteredRows = this.filteredRows.filter(row => this.filterGlobal(row, event.globalFilter)); } this.filteredRows.sort((a, b) => this.compareField(a, b, event.sortField) * event.sortOrder); this.gridData = this.filteredRows.slice(event.first, (event.first + event.rows)); this.totalRows = this.filteredRows.length; this.loading = false; }

Sue1024 avatar Dec 03 '17 08:12 Sue1024

@Sue1024 thanks a lot.

somsak-tk avatar Oct 29 '19 03:10 somsak-tk

@cagataycivici I found the cause for this bug. When using onLazyLoad, if the user sorts by a given row, $event.first will get reset to 0 as it should. However, when using filterGlobal, $event.first will remain as whatever it was. So if I go to the second page without any filter, then type in "foo", $event.first=30 and $event.globalFilter="foo". However, if I only have 23 rows with "foo" in them, my api will correctly return an empty array.

Here is my solution to this problem:

loadRequestLazy(event: LazyLoadEvent) {
...

const req = {
  skip: event.first,
  take: event.rows,
  includeInactive: this.getInactives,
  sort: sortOption,
  filter: event.globalFilter ? event.globalFilter : ''
};
// If filter changes, set skip to 0. For some reason primeng doesn't do this. But it does for sort.
if (this.previousLazyLoadRequest && this.previousLazyLoadRequest.filter !== req.filter) {
  req.skip = 0;
}
this.previousLazyLoadRequest = req;

...
}

josh-lind avatar Jul 22 '20 17:07 josh-lind

@robopec thank you it's work for me

Anuj170122 avatar Jun 18 '22 09:06 Anuj170122

@Anuj170122 how did you work on this particular issue ?

EddyMurphy95 avatar Nov 21 '23 16:11 EddyMurphy95