Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<aura:application extends="force:slds" controller="AccountListFilterByCity">
<aura:attribute name="cities" type="List" default="[]" />
<aura:attribute name="allAccounts" type="List" default="[]" />
<aura:attribute name="filterAccounts" type="List" default="[]" />
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<lightning:layout>
<lightning:layoutItem size="3">
<aura:iteration items="{!v.cities}" var="cityValue">
<lightning:input type="checkbox"
name="cityCheckbox"
label="{!cityValue}"
aura:id="cityGroup"
onchange="{!c.update}" />
</aura:iteration>
</lightning:layoutItem>
<lightning:layoutItem size="9">
<aura:iteration items="{!v.filterAccounts}" var="account">
<lightning:card title="{!account.Name}" iconName="standard:account">
{!account.BillingCity}
</lightning:card>
</aura:iteration>
</lightning:layoutItem>
</lightning:layout>
</aura:application>
public class AccountListFilterByCity {
@Auraenabled public static Account[] getRecords() {
return [SELECT Name, BillingCity FROM Account WHERE BillingCity != null];
}
}
({
init: function(component, event, helper) {
helper.init(component);
},
update: function(component, event, helper) {
helper.update(component);
}
})
({
init: function(component) {
var action = component.get("c.getRecords");
action.setCallback(this, (result) => {
var accounts = result.getReturnValue(), cities = [];
// Build a list of unique cities
accounts.forEach(
account =>
cities.indexOf(account.BillingCity) > -1 ||
cities.push(account.BillingCity)
);
// Sort alphabetically
cities = cities.sort((a, b) => a < b? -1: (a == b? 0: 1));
// Sort by city alphabetically
accounts = accounts.sort((a, b) =>
a.BillingCity < b.BillingCity? -1:
(a.BillingCity == b.BillingCity? 0: 1));
component.set("v.cities", cities);
component.set("v.allAccounts", accounts);
component.set("v.filterAccounts", accounts);
});
$A.enqueueAction(action);
},
update: function(component) {
var selectedCities = [], cityGroup = component.find("cityGroup");
// Normalize cityGroup to an array
cityGroup = cityGroup? (cityGroup.length? cityGroup: [cityGroup]): [];
// Determine selected cities
cityGroup.forEach(
city => city.get("v.checked") && selectedCities.push(city.get("v.label"))
);
// Filter accounts to selected cities, or all if no selections
component.set(
"v.filterAccounts", component.get("v.allAccounts")
.filter(account => !selectedCities.length || // No cities selected
selectedCities.indexOf(account.BillingCity) > -1) // city in selectedCities
);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment