We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Add Filter based on Checkbox

I have a Grid working Ok. And it has the internal SyncFusion Filter working ok.  However, I would like to add a couple of Checkbox Filters that can be applied to the Grid, that get applied to specific columns.


I have created a example, I this case its the Stock column (In Stock or Sold Out) and the Category column (Drawing or Photo).

Here is all I have, I would appreciate any assistance please.


<template>



    <h2>Demo</h2>
      <ul>
        <ejs-checkbox name='cleanedStock' value='In Stock' label='In Stock' ></ejs-checkbox>
        <ejs-checkbox name='cleanedStock' value='Sold Out' label='Sold Out' ></ejs-checkbox>
      </ul>
      <ul>
        <ejs-checkbox name='categoryStock' value='Photo' label='Photo' ></ejs-checkbox>
        <ejs-checkbox name='categoryStock' value='Drawing' label='Drawing' ></ejs-checkbox>
      </ul>


    <div id="app">


        <ejs-grid id="my_grid" ref='grid' :dataSource='data' :allowSorting='true' :allowFiltering='true' :filterSettings='filterOptions' :allowPaging="true" :toolbar='toolbarOptions' :created='created' >
          <e-columns>
              <e-column field='id' headerText='ID' textAlign='Right' width=75></e-column>
              <e-column field='title' headerText='Title' width=120></e-column>
              <e-column field='stockCleaned' headerText='Stock' width=100></e-column>
              <e-column field='stockCategory' headerText='Category' width=100></e-column>
              <e-column headerText='Image' width='150' textAlign='Center' :template="'tumbTemplate'"></e-column>
          </e-columns>


          <template v-slot:tumbTemplate="{data}">
              <div class="image">
                    <img :src="'https://picsum.photos/' + data.id" :alt="data.id" width="25" height="25"/>
              </div>
          </template>


      </ejs-grid>
  </div>


</template>






<script>


  import { Page, Sort, Filter, Toolbar, Search } from "@syncfusion/ej2-vue-grids"; //CommandColumn
  import { DataManager, WebApiAdaptor, Query } from "@syncfusion/ej2-data";
  import { CheckBoxComponent } from "@syncfusion/ej2-vue-buttons";


  class cleanUpGrid extends WebApiAdaptor {
    processResponse() {
      let original = super.processResponse.apply(this, arguments);


      original.forEach((item) => {
        var array = ["In Stock", "Sold Out"];
        var index = Math.floor(Math.random() * array.length);
        item['stockCleaned'] = array[index];


        array = ["Photo", "Drawing"];
        index = Math.floor(Math.random() * array.length);
        item['stockCategory'] = array[index];


        original.push(item);
      });
      original.Count = original.length;
      console.log(original);


      return original;
    }
  }




  export default({
    name: 'app',
    data() {
      return {
        data: new DataManager({
          url: 'https://jsonplaceholder.typicode.com/todos',
          adaptor: new cleanUpGrid(),
          crossDomain: true,
          offline: true,
          onSuccess: console.log("Done")
        }),


        filterOptions: {
          matchCase: false,
          operator: 'contains',
          predicate: 'and',
          ignoreAccent: true,
          type: 'Excel'
        },


        toolbarOptions: ['Search'],


        query: new Query().addParams('aaaaaaa', 'true')
      };
    },


    components: {
       "ejs-checkbox": CheckBoxComponent
     },


    methods: {


    },




    provide: {
      grid: [Page, Sort, Filter, Toolbar, Search]
    }


  });


</script>






<style>
  @import "@syncfusion/ej2-material-theme/styles/material.css";
  @import "@syncfusion/ej2-buttons/styles/material.css";
  @import "@syncfusion/ej2-popups/styles/material.css";
  @import "@syncfusion/ej2-navigations/styles/material.css";
</style>





9 Replies

JC Joseph Christ Nithin Issack Syncfusion Team April 17, 2023 09:46 PM UTC

Hi Verum,


  Greetings from Syncfusion support.


  Based on your query, you want to perform filtering based on the checked state of the external checkboxes in your sample. Your requirement can be achieved by invoking the `filterBycolumn` in the change event of the checkbox. For more details on filtering a column please refer the below documentation.


Documentaiton: https://helpej2.syncfusion.com/vue/documentation/grid/filtering/filtering

Api: https://helpej2.syncfusion.com/vue/documentation/api/grid/#filterbycolumn


Regards,

Joseph I.



VG Verum Genus April 17, 2023 10:36 PM UTC

Hello Joseph, i saw this, but was not sure how to apply it to a normal external checkbox.  The example (video) includes a way where it is sort of integrated into grid, but my checkboxes are independent of the grid.



JC Joseph Christ Nithin Issack Syncfusion Team April 27, 2023 07:10 PM UTC

Verum,



In your update, you have mentioned that you have shared a video demo but the video demo is not attached, please share the video for better understanding of your requirement.



VG Verum Genus April 27, 2023 07:13 PM UTC

Sorry, i meant the video on your linked page.


I have not been able to get any closer than the code in the first post.



VG Verum Genus May 5, 2023 07:54 PM UTC

Hi Joseph, is there any more info i can supply to help with this?


ta



VG Verum Genus May 7, 2023 08:27 PM UTC

This is my current attempt.  But when clicking the checkboxes nothing happens.



<template>







      <h2>Demo</h2>


    <ul>
      <ejs-checkbox name="cleanedStock" v-model="selectedStock" value="In Stock" label="In Stock"></ejs-checkbox>
      <ejs-checkbox name="cleanedStock" v-model="selectedStock" value="Sold Out" label="Sold Out"></ejs-checkbox>
    </ul>
    <ul>
      <ejs-checkbox name="categoryStock" v-model="selectedCategory" value="Photo" label="Photo"></ejs-checkbox>
      <ejs-checkbox name="categoryStock" v-model="selectedCategory" value="Drawing" label="Drawing"></ejs-checkbox>
    </ul>




         <div id="app">




              <ejs-grid id="my_grid" ref='grid' :dataSource='data' :allowSorting='true' :allowFiltering='true' :filterSettings='filterOptions' :allowPaging="true" :toolbar='toolbarOptions' :created='created' >
               <e-columns>
                    <e-column field='id' headerText='ID' textAlign='Right' width=75></e-column>
                    <e-column field='title' headerText='Title' width=120></e-column>
                    <e-column field='stockCleaned' headerText='Stock' width=100></e-column>
                    <e-column field='stockCategory' headerText='Category' width=100></e-column>
           <e-column headerText='Image' width='150' textAlign='Center' :template="'tumbTemplate'"></e-column>
         </e-columns>




         <template v-slot:tumbTemplate="{data}">
           <div class="image">
            {{ data.id }}
              <!-- <img :src="'https://picsum.photos/' + data.id" :alt="data.id" width="25" height="25"/> -->
           </div>
         </template>




       </ejs-grid>
     </div>




    </template>




    <script>




     import { Page, Sort, Filter, Toolbar, Search } from "@syncfusion/ej2-vue-grids"; //CommandColumn
     import { DataManager, WebApiAdaptor, Query } from "@syncfusion/ej2-data";
     import { CheckBoxComponent } from "@syncfusion/ej2-vue-buttons";




     class cleanUpGrid extends WebApiAdaptor {
      processResponse() {
       let original = super.processResponse.apply(this, arguments);




       original.forEach((item) => {
        var array = ["In Stock", "Sold Out"];
        var index = Math.floor(Math.random() * array.length);
        item['stockCleaned'] = array[index];




        array = ["Photo", "Drawing"];
        index = Math.floor(Math.random() * array.length);
        item['stockCategory'] = array[index];




        original.push(item);
       });
       original.Count = original.length;
       console.log(original);




       return original;
      }
     }








     export default({
        name: 'app',
        created(){
            this.checkedStock = [];
            this.checkedCategory = [];
        },
      data() {
       return {
        data: new DataManager({
        url: 'https://jsonplaceholder.typicode.com/todos',
            adaptor: new cleanUpGrid(),
            crossDomain: true,
            offline: true,
            onSuccess: console.log("Done")
        }),




        filterOptions: {
            matchCase: false,
            operator: 'contains',
            predicate: 'and',
            ignoreAccent: true,
            type: 'Excel'
        },




        checkedStock: [],
        checkedCategory: [],


        toolbarOptions: ['Search'],




        query: new Query().addParams('aaaaaaa', 'true')
       };
      },




        components: {
            "ejs-checkbox": CheckBoxComponent
        },


        methods: {
      filterStock() {
        this.checkedStock = [];
        document.querySelectorAll('input[name="cleanedStock"]').forEach((el) => {
          if (el.checked) {
            this.checkedStock.push(el.value);
          }
        });
        this.filterData();
      },
      filterCategory() {
        this.checkedCategory = [];
        document.querySelectorAll('input[name="categoryStock"]').forEach((el) => {
          if (el.checked) {
            this.checkedCategory.push(el.value);
          }
        });
        this.filterData();
      },
      filterData() {
        let query = new Query();
        if (this.checkedStock.length > 0) {
          query = query.where('stockCleaned', 'in', this.checkedStock);
        }
        if (this.checkedCategory.length > 0) {
          query = query.where('stockCategory', 'in', this.checkedCategory);
        }
        this.$refs.grid.query = query;
        this.$refs.grid.refresh();
      }
    },


        provide: {
            grid: [Page, Sort, Filter, Toolbar, Search]
        }


    });


</script>


<style>
    @import "@syncfusion/ej2-material-theme/styles/material.css";
    @import "@syncfusion/ej2-buttons/styles/material.css";
    @import "@syncfusion/ej2-popups/styles/material.css";
    @import "@syncfusion/ej2-navigations/styles/material.css";
</style>






thanks



HS Hemanthkumar S Syncfusion Team May 9, 2023 03:13 PM UTC

Hi Verum Genus,


Query: when clicking the checkboxes nothing happens


After reviewing the code snippet you provided, we noticed that the change event of the Syncfusion EJ2 Checkbox is not being called. The change event is triggered whenever the CheckBox state has been modified by user interaction. As per your request, we have created a sample that includes a change event for the Checkbox, which can help you achieve your objective.

For more information, please refer to the below code example, API, GIF, and sample.

[App.vue]

 

  <ejs-checkbox

    label="Filter France"

    name="country"

    :change="onCheckBoxChange"

    value="France"

  ></ejs-checkbox>

 

  methods: {

    onCheckBoxChange(args) {

      this.country = [];

      document.querySelectorAll('input[name="country"]').forEach((el=> {

        if (el.checked) {

          this.country.push(el.value);

        }

      });

      this.filterData();

    },

    filterData() {

      if (this.country.length > 0) {

        this.$refs.grid.filterByColumn('ShipCountry''equal'this.country);

      } else {

        this.$refs.grid.clearFiltering();

      }

    },

  },

 


Change Event API: https://helpej2.syncfusion.com/vue/documentation/api/check-box/checkBoxModel/#change

Sample Link: https://stackblitz.com/edit/vue-xv433e?file=src%2FApp.vue


Please feel free to contact us if you require any further assistance. We are always available and eager to help you in any way we can.


Regards,

Hemanth Kumar S


Attachment: gif_ff3d23d2.zip


VG Verum Genus May 9, 2023 08:43 PM UTC

Thank you!, that did the trick.


A heads up.  When unticking checkboxes it does not update the filter until all are unticked.  As such I added a clear before applying the filter, now it updates on each untick:


Not sure if this is by design or a bug.

    filterData() {
this.$refs.grid.clearFiltering();
      if (this.country.length > 0) {
        this.$refs.grid.filterByColumn('ShipCountry''equal'this.country);
      } else {
        this.$refs.grid.clearFiltering();
      }
    },


HS Hemanthkumar S Syncfusion Team May 15, 2023 09:36 AM UTC

Hi Verum Genus,


Query: When unticking checkboxes it does not update the filter until all are unticked


From the provided sample, we successfully replicated the mentioned issue. The filterSettings.columns property helps to get the columns that were currently filtered. Considering your update, we have prepared a sample and suggest clearing the previously filtered value for the corresponding column using the filterSettings.columns property before invoking the filterByColumn method of the Grid.


For information, please refer to the below code example, API, and sample.

[App.vue]

    filterData() {

      if (this.country.length > 0) {

        const grid = document.getElementById('grid1').ej2_instances[0];

        grid.filterSettings.columns = grid.filterSettings.columns.filter(

          (item=> item.field !== 'ShipCountry'

        );

        this.$refs.grid.filterByColumn('ShipCountry''equal'this.country);

      } else {

        this.$refs.grid.clearFiltering();

      }

    }

 


filterSettings.columns API: https://ej2.syncfusion.com/documentation/api/grid/filterSettings/#columns


Sample Link: https://stackblitz.com/edit/vue-trcbfi?file=src%2FApp.vue


Please feel free to contact us if you require any further assistance. We are always available and eager to help you in any way we can.


Regards,

Hemanth Kumar S


Loader.
Up arrow icon