Implementation of Dynamic Search in Salesforce Lightning Component



Today, I am sharing the code, that, how you can implement Dynamic Search using Lightning Component. For this task, we need three things:-
  1. A Lightning Component Bundle
  2. A Lightning Application Bundle
  3. An Apex Controller.
Apex Controller-
public class AccountShowController {
@AuraEnabled
public static List<Account> showAccounts()
{
return [SELECT Id, Name, Phone, AnnualRevenue From Account];
}




Lightning Component –

<aura:component controller="AccountShowController" >
<aura:attribute name="Account" type="Account[]" />
<aura:attribute name="SearchKey" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.myAction}"/>
<div class="slds-form-element">
<label class="slds-form-element__label" for="text-input-id-1">Input Label</label>
<div class="slds-form-element__control">
<input type="text" value="{!v.SearchKey}" onkeyup="{!c.myFunction}" id="myInput" class="slds-input" placeholder="Search Accounts" />
</div>
</div>
<br/>
<table class="slds-table slds-table--bordered" id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>AnnualRevenue</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.Account}" var="a">
<tr>
<td>{!a.Name}</td>
<td>{!a.Phone}</td>
<td>{!a.AnnualRevenue}</td>
</tr>
</aura:iteration>
</tbody>
</table>
</aura:component>
view raw AccountShow.cmp hosted with ❤ by GitHub

JavaScript Controller –
({
myAction : function(component, event, helper) {
var action = component.get("c.showAccounts");
action.setCallback(this, function(response){
var state=response.getState();
if(state === 'SUCCESS')
{
component.set("v.Account", response.getReturnValue());
}
else
{
alert("error");
}
});
$A.enqueueAction(action);
},
myFunction:function(component, event, helper) {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
//input = component.get("v.SearchKey");
//var input = component.find("myInput").get("v.value");
console.log(input.value);
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
//console.log(tr.length)
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
})


Lightning Application-
<aura:application extends="force:slds">
<c:AuraIterationTable />
</aura:application>

Thanks.
Happy Coding.

Next Post Previous Post
No Comment
Add Comment
comment url