0

I have tried using filters in a lightning component which filters records based on criteria. How can I toggle the filter based on true or false of a checkbox.

The issue I have currently is when ik toggle the checkbox back I do not get my old results and cant combine this dynamically with more filters. See my code below.

Checkbox

<lightning:input type="checkbox" label="Workshop" onchange="{!c.Workshop}"/>

Filter

 Workshop : function(component, event) {
    var itemList = component.get("v.opleidingen");
    var newList = [];
    for (var item of itemList){
     if(item.Opleidingstype__c  === 'Workshop'){
    newList.push(item);
    }
    component.set('v.opleidingen',newList);    
    }}
1

The issue seems to be that you are completely overwriting the original list. To avoid this, you can save the full list to another attribute on the component and display a filtered version. You are also not actually checking the value of the checkbox, so your condition is always being applied.

Your component might look more like this:

<lightning:attribute name="originalList" type="Object[]" /> /*Populate this with the full list*/ 
<lightning:attribute name="isWorkshop" type="Boolean" />

<lightning:input type="checkbox" label="Workshop" onchange="{!c.Workshop}" checked="{!v.isWorkshop}"/>

And your controller:

Workshop : function(component, event) {
var isWorkshopFilter = component.get("v.isWorkshop");
var fullList = component.get("v.originalList");
var filteredList = [];
for (var item of itemList){
 if(isWorkshopFilter && item.Opleidingstype__c  === 'Workshop'){
newList.push(item);
}
component.set('v.opleidingen',filteredList);    
}}

Note that we added the binding of the "checked" attribute on the checkbox to a new attribute, and then used that in the if condition of the loop.

  • I tried the following: doInit : function(component, event) { var action = component.get("c.findAll"); action.setCallback(this, function(a) { component.set("v.originalList", a.getReturnValue()); }); $A.enqueueAction(action); } <aura:attribute name="originalList" type="Opleiding__c[]" /> <aura:attribute name="isWorkshop" type="Boolean" /> Error:Failing descriptor: {c:OpleidingenList} – Thomas Jan 25 '18 at 20:36
  • Did you add the new attributes to the controller file? They should be added to the component markup file. – Ryan Rudd Jan 25 '18 at 20:45
  • Yes to the component markup. The only difference is the aura part: <aura:attribute name="originalList" type="Opleiding__c[]" /> <aura:attribute name="isWorkshop" type="Boolean" /> – Thomas Jan 25 '18 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.