filter is not working, which I did incorrectly

1 Answer 78 Views
Grid
Przemyslaw
Top achievements
Rank 1
Przemyslaw asked on 15 Jul 2022, 08:40 AM
  <!-- :data-items="result" uwaga to jest do filtru potrzebne -->
<template>
<div class="example-wrapper">
  <Grid
    ref="grid"
    :style="{ height: '860px' }"
    :data-items="result"  
    :selected-field="selectedField"
    :sortable="true"
    :sort="sort"
    :pageable="pageable"
    :take="take"
    :skip="skip"
    :total="total"
    :filterable="true"
    :filter="filter"
     :loader="loader"
    @filterchange="filterChangeHandler"
    @itemchange="itemChange"
    @datastatechange="dataStateChange"
    :columns="columns"
    @selectionchange="onSelectionChange"
    @headerselectionchange="onHeaderSelectionChange"
    @rowclick="onRowClick"
  >
    <template v-slot:myTemplate="{props}">
      <custom  :data-item="props.dataItem"
        @edit="edit"
        @save="save"
        @remove="remove"
        @cancel="cancel"
      />
     
    </template>
    <grid-toolbar >
       
      <kbutton title="Add new" :theme-color="'primary'" @click="insert">
       Dodaj rekord
   
      </kbutton>  <br>
      <kbutton title="Add new" :theme-color="'primary'" @click="insert">
       Zaznacz zrobione
   
      </kbutton>  
  <div class="demo">
     <span class="wrapper">
        <checkbox   :id="'chb1'" :label="'Przeglądy maszyn '" @click="testowyfiltr"/>
        <checkbox   :id="'chb2'" :label="'Przeglądy wytwarzanie '"  />
        <checkbox   :id="'chb3'"  :label="'Przeglądy infrastryktrua '"  />
        </span>
    </div>
      <kbutton
        v-if="hasItemsInEdit"
        title="Cancel current changes"
        @click="cancelChanges"
      >
        Cancel current changes
      </kbutton>
       <div class="demo2">
         <span class="wrapper">
          <h3 :style="{ color: 'black' }" > W tym tygodniu do wykonania </h3> <h2  :style="{ color: 'red' }"> 5 </h2> <h3 :style="{ color: 'black' }">przeglądów</h3>
      </span>
      </div>
    </grid-toolbar>
 
   
    <grid-norecords> poczekaj.....</grid-norecords>
  </Grid>
   <dialog-container  
        v-if="productInEdit"  
        :data-item="productInEdit"
        @save="save"
        @cancel="cancel"
         :products-list="products">
       
        </dialog-container>
        </div>
</template>
<script>
import { Grid, GridToolbar, GridNoRecords } from '@progress/kendo-vue-grid';
import { Button } from '@progress/kendo-vue-buttons';
import { process, toODataString } from '@progress/kendo-data-query';
import CommandCell from './CommandCell';
import DialogContainer from './DialogContainer';
import { Checkbox } from "@progress/kendo-vue-inputs";
// const allData = [{text: 'do zrobienia'},{text: 'zrobione'}];
export default {
  components: {
    Grid: Grid,
    'grid-toolbar': GridToolbar,
    'grid-norecords': GridNoRecords,
    custom: CommandCell,
    kbutton: Button,
    'dialog-container': DialogContainer,
      checkbox: Checkbox
  },
  data: function () {
    return {
     
      //  products: allData,
       selectedField: 'selected',
    //   gridData: gridData.map(item => { return {...item, selected: false} }),
      productInEdit: undefined,
      baseUrl: 'http://156.4.10.182:42471/test/products',
      init: { method: 'GET', accept: 'application/json', headers: {} },
      filter: null,
      sort: null,
      pageable: true,
      skip: 0,
      take: 10,
      total: 0,
      // expand: "Supplier",
      updatedData: [],
      editID: null,
      staticColumns: [
        { field: 'Id', filterable:false, editable: false, width: 50, title: 'id' },
       
        // { field: 'LP',filterable:false ,width: 40},
        { field: 'Nazwa_maszyny' ,filterable:false ,width: 200 ,title: 'Nazwa Maszyny'},
        { field: 'Urzadzenie' , filterable:false ,width: 250 ,title: 'Urządzenie'},
         { field: 'Czynnosc' , filterable:false ,width: 200 ,title: 'Czynnosc'},
        { field: 'Grupa' , filterable:false ,width: 70 ,title: 'Grupa'},
     
        // { field: 'Priorytet',filterable:false ,width: 100 ,title: 'Priorytet'},
        { field: 'Lokalizacja' , filterable:false ,width: 120 ,title: 'Lokalizacja'},
        { field: 'Wykonawca' , filterable:false ,width: 60 ,title: 'Wykonawca'},
        { field: 'Tydzien' , filterable:true ,width: 100 ,title: 'Tydzien'},
         { field: 'Link' , filterable:true ,width: 100 ,title: 'Link'},
           { field: 'Foto',filterable:false,width: 100 ,title: 'Foto' , cell: this.cellFunction},
       { field: 'Status', filterable:false ,width: 100 },
        // { field: 'Data', filterable:false ,title: 'Data', editor: 'numeric', width: 80 },
        { field: 'Dod_info',filterable:false,width: 100 ,title: 'Dod_info'},
      //   { field: 'Login' ,width: 100 ,title: 'Login'},
     
        { cell: 'myTemplate', filterable: false, width: '110px' },
      ],
      gridData: [],
       loader: true,
    };
  },
  computed: {
    areAllSelected () {
            return this.gridData.findIndex(item => item.selected === false) === -1;
        },
        columns () {
            return [
                { field: 'selected',filterable:false, width: '50px', headerSelectionValue: this.areAllSelected },
                ...this.staticColumns
            ]
        },
    hasItemsInEdit() {
      return this.gridData.filter((p) => p.inEdit).length > 0;
    },
    dataState() {
      return {
        sort: this.sort,
        skip: this.skip,
        take: this.take,
   
      };
    },
    result: {
      get: function () {
        // console.log(this.gridData)
        return process(this.gridData, {
           sort: this.sort,
           filter: this.filter,
           take: this.take,
           skip: this.skip,
        });
      },
    },
 
  },
 
  created: function () {
    this.getData();
  },
  methods: {
    cellFunction: function (h, tdElement , props, listeners ) {
            return h('td', {
                on: {
                    click: function(e){
                        listeners.custom(e);
                    }
                }
            }, [<img src="https://en.pimg.jp/047/504/268/1/47504268.jpg"/>]);
        },
   
filterChangeHandler(event) {
    this.filter = event.filter;
  },
    onHeaderSelectionChange (event) {
            let checked = event.event.target.checked;
            this.gridData = this.gridData.map((item) => { return {...item, selected: checked} });
        },
        onSelectionChange (event) {
            event.dataItem[this.selectedField] = !event.dataItem[this.selectedField];
        },
        onRowClick (event) {
            event.dataItem[this.selectedField] = !event.dataItem[this.selectedField];
        },
        createRandomData(count) {
            return
        },
   
    updateService(action = '', item) {
      const that = this;
      const idIfNeeded =
        action === 'DELETE' || action === 'PUT' ? `(${item.Id})` : '';
      const url = this.baseUrl + idIfNeeded;
     
      const body =
        action === 'POST' || action === 'PUT'
          ? JSON.stringify({
              Id: item.Id,
              Status: item.Status,
              Data : item.Data,
              LP : item.LP,
              Nazwa_maszyny: item.Nazwa_maszyny,
              Urzadzenie: item.Urzadzenie,
              Grupa: item.Grupa,
              Foto: item.Foto,
              Priorytet: item.Priorytet,
              Lokalizacja: item.Lokalizacja,
              Wykonawca: item.Wykonawca,
              Tydzien: item.Tydzien,
              Druk: item.Druk,
              Dod_info: item.Dod_info,
              Login: item.Login
            })
           :{};
            console.log(body);
         fetch(url, {
        method: action,
        accept: 'application/json',
        headers: {
          'Content-type': 'application/json',
        },
        body: body,
      }).then((response) => {
        if (response.ok) {
          that.getData();
        } else {
          alert('request failed');
        }
      });
    },
    itemChange: function (e) {
      if (e.dataItem.Id) {
        let index = this.gridData.findIndex(
          (p) => p.Id === e.dataItem.Id
        );
        let updated = Object.assign({}, this.gridData[index], {
          [e.field]: e.value,
        });
        this.gridData.splice(index, 1, updated);
      } else {
        e.dataItem[e.field] = e.value;
      }
    },
    insert() {
       this.productInEdit = { };
           
    },
    testowyfiltr(event){
     
      this.filter = event.filter;
    },
    edit(dataItem) {
     
      this.productInEdit = this.cloneProduct(dataItem);
     
    },
    save(e) {
     
    const dataItem = this.productInEdit;
    const item = this.gridData.slice();
    const isNewProduct = dataItem.Id === undefined;
   
      if(isNewProduct) {
            item.unshift(this.newProduct(dataItem));
           this.updateService(dataItem.Id ? 'PUT' : 'POST', dataItem);
        } else {
       const index = item.findIndex(p => p.Id === dataItem.Id);
       item.splice(index, 1, dataItem.Id);
       let items = this.gridData[index];
 
       this.updateService(items.Id ? 'PUT' : 'POST', dataItem) ;
    item.unshift(this.newProduct(dataItem));
           this.updateService(dataItem.Id ? 'PUT' : 'POST', dataItem);
        }
       this.productInEdit= undefined;
    },
    cancel(e) {
      this.productInEdit= undefined;
    },
    remove(e) {
 
    this.updateService('DELETE', e);
       this.productInEdit= undefined;
    },
    cancelChanges() {
      this.getData();
    },
    getData: function (initial) {
      const myDataState = JSON.parse(JSON.stringify(this.dataState));
      const that = this;
      fetch(
        this.baseUrl + '?' + toODataString(myDataState) + '&$count=true',
            // this.baseUrl + '?' + toODataString(this.dataState) + '&$count=true' +'&$expand=Supplier',
        this.init
      )
        .then((response) => response.json())
        .then((json) => {
          const total = json['@odata.count'];
          const data = json['value'];
          that.total = total;
          that.updatedData = [...data];
          that.gridData = data;
        });
    },
    createAppState: function (dataState) {
      this.take = dataState.take;
      this.skip = dataState.skip;
      this.filter = "Luty";
      this.sort = dataState.sort;
   
   this.getData();
    },
    dataStateChange: function (event) {
     
      this.createAppState(event.data);
    },
    cloneProduct(product) {
          return Object.assign({}, product);
         
      },
    newProduct(source) {
     
          const id = this.gridData.reduce((acc, current) => Math.max(acc, current.Id || 0), 0) + 1;
     
          const newProduct = {
              Id: id,
              Status: "",
              Data : "",
              LP : "",
              Nazwa_maszyny: "",
              Urzadzenie: "",
              Grupa: "",
              Foto: "",
              Priorytet: "",
              Lokalizacja: "",
              Wykonawca: "",
              Tydzien: "",
              Druk: "",
              Dod_info: "",
              Login: ""
          };  
          return Object.assign(newProduct, source);
         
      }
  },
};
</script>
<style>
.custom-checkbox input {
  width: 30px;
  height: 30px;
}
.wrapper {
  padding: 20px;
  display: flex;
  flex-direction: row;
}
.demo {
  display: flex;
  flex-direction: row;
  justify-content: left;
}
.demo2 {
  display: flex;
  flex-direction: row;
  justify-content: left;
}
 .k-grid .k-toolbar {
        background-color: rgb(224, 225, 187);
    }
       
</style>

1 Answer, 1 is accepted

Sort by
0
Petar
Telerik team
answered on 15 Jul 2022, 10:21 AM

Hi, Przemyslaw.

As we managed to resolve the issue in a private ticket, I am sharing an edited version of my answer below. I am doing this, just in case someone from the community experience a similar issue and needs a solution.

From the shared code I can see two things:

Change suggestion 1: Remove the filterchange event from the definition of the Grid. If you test it, you will see that when the filterchange is removed, once you make filtering inside the Grid, the datastatechange event is triggered. 

When the datastatechange is triggered, it will execute the createAppState method:

createAppState: function (dataState) {
      this.take = dataState.take;
      this.skip = dataState.skip;
      this.filter = dataState.filter;
      this.sort = dataState.sort;
   
      this.getData();
}

Change suggestion 2: The other thing I can see is the following computed property:

result: {
      get: function () {
        // console.log(this.gridData)
        return process(this.gridData, {
           sort: this.sort,
           filter: this.filter,
           take: this.take,
           skip: this.skip,
        });
      },
}

The result computed property is passed to the dataItems of the Grid. In the getData method, you are correctly assigning the data value to the gridData property(see the code in yellow below).

    getData: function (initial) {
      const myDataState = JSON.parse(JSON.stringify(this.dataState));
      const that = this;
      fetch(
        this.baseUrl + '?' + toODataString(myDataState) + '&$count=true',
            // this.baseUrl + '?' + toODataString(this.dataState) + '&$count=true' +'&$expand=Supplier',
        this.init
      )
        .then((response) => response.json())
        .then((json) => {
          const total = json['@odata.count'];
          const data = json['value'];
          that.total = total;
          that.updatedData = [...data];
          that.gridData = data;
        });
    }

With the above assignment, the result computed property is re-calculated for a second time again with the dataState properties. The thing is that the gridData value already has the values of the Grid's filters, sorting, etc. applied to it, from the server. So, my second suggestion is to remove the result computed property and define the Grid dataItems as follows:

:data-items="gridData"

Please apply the two, suggested above, changes and let me know about the result. 

Regards,
Petar
Progress Telerik

The Premier Dev Conference is back! 

Coming to you live from Progress360 in-person or on your own time, DevReach for all. Register Today.


Tags
Grid
Asked by
Przemyslaw
Top achievements
Rank 1
Answers by
Petar
Telerik team
Share this question
or