function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
imKTimKT 

Lightning component is not working...

Hi everyone,
I am trying to search Account records using Lightning Component but functionality is not working. Please help me to find out where I did wrong.

Component:
<aura:component controller="AccountListController" implements="force:appHostable">
    <aura:attribute name="acList" type="Account[]" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:handler event="c:SearchKeyChange" action="{!c.searchKeyChange}"/>
    <div class="slds-grid">
        <div class="slds-col slds-align-bottom" style="margin-top:10px">
            <c:SearchResultComponent />
        </div>
    </div>
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
        <thead>
            <tr class="slds-text-heading_label">
                <th scope="col"><div class="slds-truncate" title="Id">Id</div></th>
                <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
                <th scope="col"><div class="slds-truncate" title="Type">Type</div></th>
                <th scope="col"><div class="slds-truncate" title="AccountNumber">Account Number</div></th>
                <th scope="col"><div class="slds-truncate" title="Industry">Industry</div></th>
            </tr>
        </thead>
        <tbody>
            <!-- Use the Apex model and controller to fetch server side data -->
            <aura:iteration items="{!v.acList}" var="ac">
                <tr>
                    <th scope="row">
                        <div class="slds-truncate" title="{!ac.Id}">
                            <a href="{! '#/sObject/' + ac.Id + '/view'}">{!ac.Id}</a>
                        </div>
                    </th>
                    <td><div class="slds-truncate" title="{!ac.Name}">{!ac.Name}</div></td>
                    <td><div class="slds-truncate" title="{!ac.Type}">{!ac.Type}</div></td>
                    <td><div class="slds-truncate" title="{!ac.AccountNumber}">{!ac.AccountNumber}</div></td>
                    <td><div class="slds-truncate" title="{!ac.Industry}">{!ac.Industry}</div></td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>
Js Controller:
({
	doInit : function(component, event, helper) {
		helper.getAccountList(component); 
	},
    searchKeyChange : function(component, event) {
        var searchKey = event.getParam("searchKey");
        //console.log('@@@@@@@search Value====',searchValue);
        var accList = component.get("v.acList");
        var action =  component.get('c.findByName');
        //console.log('action Value====',action);
        action.setParam({
            "searchKey" : searchKey,
            "accList" : accList
        });
        
        action.setCallback(this, function(result){
            component.set('v.acList', result.getReturnValue());
        });
        $A.enqueueAction(action);
    },
})
Helper Js:
({
    getAccountList : function(component) {
        var action = component.get('c.getAccounts');
        action.setCallback(this,function(result){
            component.set('v.acList', result.getReturnValue());
        });
        $A.enqueueAction(action);
    },
})
Server side Controller:
public class AccountListController {
    
    @AuraEnabled 
    public static list<Account> getAccounts(){
        return[select id, name , Type, Industry, AccountNumber from Account ORDER BY createdDate ASC];
    }
    
    @AuraEnabled
    public static list<Account> findByName(String searchKey, Account[] accList){
        Set<Id> recordIds = new Map<Id, Account>(getAccounts()).keySet();
        System.debug('recordIds@@@@@@'+' '+recordIds);
        System.debug('ACCOUNT LIST' + accList);
        String searchName = searchKey + '%';
        return[ SELECT id, Name, Industry, Type, AccountNumber FROM Account WHERE (Name LIKE : searchName OR AccountNumber LIKE :searchName OR Type LIKE :searchName OR Industry LIKE :searchName) AND Id IN:recordIds];
    }
}

Search Result comp:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	<div>
        <input type="text" class="form-control" placeholder="Search Account.." onkeyup="{!c.searchKeyChange}"/>
    </div>
</aura:component>

Js controller:
({
    searchKeyChange : function(component, event, helper) {
        var appevt = $A.get("e.c:SearchKeyChange");
        appevt.setParam({
            "searchKey" : event.target.value
        });
        appevt.fire();
    },
    
})


 
Deepali KulshresthaDeepali Kulshrestha
Hi,
Greetings to you!

 I read your problem and implemented in my Org. Please use the below code [Solved] : -
 
Component : -

    <aura:component controller="searchAccountController">

            <!-- CREATE ATTRIBUTE/VARIABLE-->
            <aura:attribute name="searchResult" type="List" description="use for store and display account list return from server"/>
            <aura:attribute name="searchKeyword" type="String" description="use for store user search input"/>
            <aura:attribute name="Message" type="boolean" default="false" description="use for display no record found message"/>
            <aura:attribute name="TotalNumberOfRecord" type="integer" default="0" description="use for display Number of records"/>

            <!-- SHOW LOADING SPINNER-->
            <lightning:spinner variant="brand" size="large" aura:id="Id_spinner" class="slds-hide" />

            <div class="slds-m-around_medium">
                    <!-- SEARCH INPUT AND SEARCH BUTTON-->
                    <lightning:layout>
                            <lightning:layoutItem size="3" padding="around-small">
                                    <lightning:input value="{!v.searchKeyword}"
                                                     required="true"
                                                     placeholder="search Accounts.."
                                                     aura:id="searchField"
                                                     label="Account Name"/>
                            </lightning:layoutItem>
                            <lightning:layoutItem size="2" padding="around-small">
                                    <lightning:button onclick="{!c.Search}"
                                                      variant="brand"
                                                      label="Search"
                                                      iconName="utility:search"/>
                            </lightning:layoutItem>
                    </lightning:layout>

                    <!-- TOTAL RECORDS BADGES-->
                    <div class="slds-m-around_x-small">
                            <lightning:badge label="{!v.TotalNumberOfRecord}" />
                    </div>

                    <!-- ERROR MESSAGE IF NOT RECORDS FOUND-->
                    <aura:if isTrue="{!v.Message}">
                            <div class="slds-notify_container slds-is-relative">
                                    <div class="slds-notify slds-notify_toast slds-theme_error" role="alert">
                                            <div class="slds-notify__content">
                                                    <h2 class="slds-text-heading_small">No Records Found...</h2>
                                            </div>
                                    </div>
                            </div>
                    </aura:if>

                    <!-- TABLE CONTENT-->
                    <table class="slds-table slds-table_bordered slds-table_cell-buffer">
                            <thead>
                            <tr class="slds-text-title_caps">
                                    <th scope="col">
                                            <div class="slds-truncate" title="S.no">S.no</div>
                                    </th>
                                    <th scope="col">
                                            <div class="slds-truncate" title="Account Name">Account Name</div>
                                    </th>
                                    <th scope="col">
                                            <div class="slds-truncate" title="Type">Type</div>
                                    </th>
                                    <th scope="col">
                                            <div class="slds-truncate" title="Industry">Industry</div>
                                    </th>
                                    <th scope="col">
                                            <div class="slds-truncate" title="Phone">Phone</div>
                                    </th>
                                    <th scope="col">
                                            <div class="slds-truncate" title="Fax">Fax</div>
                                    </th>
                            </tr>
                            </thead>
                            <tbody>
                            <!--### display all records of searchResult attribute by aura:iteration ###-->
                            <aura:iteration items="{!v.searchResult}" var="acc" indexVar="count">
                                    <tr>
                                            <td>
                                                    <div class="slds-truncate">{!count + 1}</div>
                                            </td>
                                            <td>
                                                    <div class="slds-truncate">{!acc.Name}</div>
                                            </td>
                                            <td>
                                                    <div class="slds-truncate">{!acc.Type}</div>
                                            </td>
                                            <td>
                                                    <div class="slds-truncate">{!acc.Industry}</div>
                                            </td>
                                            <td>
                                                    <div class="slds-truncate">{!acc.Phone}</div>
                                            </td>
                                            <td>
                                                    <div class="slds-truncate">{!acc.Fax}</div>
                                            </td>
                                    </tr>
                            </aura:iteration>
                            </tbody>
                    </table>
            </div>
    </aura:component>
 
JS Controller :  -

    ({
        Search: function(component, event, helper) {
            var searchField = component.find('searchField');
            var isValueMissing = searchField.get('v.validity').valueMissing;
            // if value is missing show error message and focus on field
            if(isValueMissing) {
                searchField.showHelpMessageIfInvalid();
                searchField.focus();
            }else{
              // else call helper function 
                helper.SearchHelper(component, event);
            }
        },
    })
 
JS Helper : - 

    ({
        SearchHelper: function(component, event) {
            // show spinner message
             component.find("Id_spinner").set("v.class" , 'slds-show');
            var action = component.get("c.fetchAccount");
            action.setParams({
                'searchKeyWord': component.get("v.searchKeyword")
            });
            action.setCallback(this, function(response) {
               // hide spinner when response coming from server 
                component.find("Id_spinner").set("v.class" , 'slds-hide');
                var state = response.getState();
                if (state === "SUCCESS") {
                    var storeResponse = response.getReturnValue();
                    
                    // if storeResponse size is 0 ,display no record found message on screen.
                    if (storeResponse.length == 0) {
                        component.set("v.Message", true);
                    } else {
                        component.set("v.Message", false);
                    }
                    
                    // set numberOfRecord attribute value with length of return value from server
                    component.set("v.TotalNumberOfRecord", storeResponse.length);
                    
                    // set searchResult list with return value from server.
                    component.set("v.searchResult", storeResponse); 
                    
                }else if (state === "INCOMPLETE") {
                    alert('Response is Incompleted');
                }else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            alert("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        alert("Unknown error");
                    }
                }
            });
            $A.enqueueAction(action);
        },
    })
 
Controller Class : - 

    public with sharing class searchAccountController {

        @AuraEnabled
        public static List < account > fetchAccount(String searchKeyWord) {
            String searchKey = searchKeyWord + '%';
            List < Account > returnList = new List < Account > ();
            List < Account > lstOfAccount = [select id, Name, Type, Industry, Phone, Fax from account
            where Name LIKE: searchKey LIMIT 500];

            for (Account acc: lstOfAccount) {
            returnList.add(acc);
            }
            return returnList;
        }
    }

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.
imKTimKT
@Deepali,
I don't need button for searching records in this scenario. If I have more than 3 records which starts from A. like ABC, Amar, Amir .
Suppose  I put Am in searchbox then 2 records should be shown or If I type Ama then only Amar should be shown.
I hope you understand that.
 
Ramakrishna Reddy GouniRamakrishna Reddy Gouni
<aura:attribute name="searchKey" type="string" />
<aura:handler name="change" value="{!v.searchKey}" action="{!c.searchKeyChange}"/>
<lightning:input type="text" name="searchKey" value="{!v.searchKey} "/>

OR 

<aura:attribute name="searchKey" type="string" />
<lightning:input type="text" name="searchKey" value="{!v.searchKey} " onkeyup="{!c.searchKeyChange}" />

 
Deepali KulshresthaDeepali Kulshrestha
Hi,
Greetings to you!

- You have not used aura:registerEvent in SearchResultComponent.
- Please use the below line .
 
<aura:registerEvent name="appevt" type="c:SearchKeyChange"/>

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.