0

Apex Class -

public 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, Phone, Type from account
                                   where Name LIKE: searchKey LIMIT 500];

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

}

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"/>   -->



    <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"
                                 onkeyup="{!c.Search}"/>
            </lightning:layoutItem>
        </lightning:layout>


        <!-- 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>



        <aura:if isTrue="{!v.searchKeyword}">

                <!--### display all records of searchResult attribute by aura:iteration ###-->
            <div class="forSearchBar">
                <aura:iteration items="{!v.searchResult}" var="acc" indexVar="count">

                        <div class="slds-truncate" onClick="navigate">{!acc.Name}</div> 
                </aura:iteration>
            </div>
            <aura:set attribute="else">
             <div class="forSearchBar"> False  </div>  
            </aura:set>
        </aura:if>
    </div>
</aura:component>

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);
        }
    },

})

Helper -

({
    SearchHelper: function(component, event) {
        // show spinner message
        var action = component.get("c.fetchAccount");
        action.setParams({
            'searchKeyWord': component.get("v.searchKeyword")
        });
        action.setCallback(this, function(response) {
            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 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);
    },
})

Application:-

<aura:application extends="force:slds">
   <qwerty:searchAccount/>
</aura:application>
  • 1
    Hi. Pls tell us what your actual issue is and what you tried so far to resolve it. – Guy Clairbois Nov 21 '19 at 12:24
  • Actually when you will go through the code there is a search box input type which gives the list of account.. I want to click on any account then to navigate the details of account – Sangeet Nov 21 '19 at 13:06
  • once you click Account name you want list of accounts page redirect to account detail or you want open as new browser page with account details? – sdandamud1 Nov 21 '19 at 14:25
  • i want toopen account detail page – Sangeet Nov 21 '19 at 15:02
0

i have found 2 issues in your code

  1. you have to use onclick but in your code used capital "C".
  2. any click events in component is starts with !c. value provider. but in your case are not used valid syntax

    onClick="navigate" {!acc.Name}`.

so your code should be:

<div class="slds-truncate" onclick="{!c.navigate}">{!acc.Name}</div>
|improve this answer|||||
  • Thanks, sdandamud1 Its working fine navigation is working good, Can you just please help me out that how to define url in window.open for opening records of account because i am new in lightning so still i am not able to solve it, I searched on internet also but not get any solution... Please help me out – Sangeet Nov 22 '19 at 5:22
  • please accept and upvote if my solution works, for opening a record details page please come as new question. – sdandamud1 Nov 22 '19 at 13:59
0

In the component you have to call a controller's method using "{!c.methodName}". also you can store the Account id on the DOM element. To navigate to the Account we can use the Navigation service. So you have to change the component code as below. Add the navigation service at the start of the component.

<aura:component controller="searchAccountController">
<lightning:navigation aura:id="navService"/>

And change your code in the iteration as below.

<aura:iteration items="{!v.searchResult}" var="acc" indexVar="count">
           <div class="slds-truncate" data-value="{!acc.Id}" onClick="{!c.navigate}">{!acc.Name}
           </div> 
 </aura:iteration>

You have to add "navigate" method to the controller.

navigate: function(component, event, helper){
var component_target = event.currentTarget;
        var recordId = component_target.dataset.value;
        var navService = component.find("navService");
        var pageReference = {    
            "type": "standard__recordPage", 
            "attributes": {
                "recordId": recordId, 
                "actionName": "view"
            } 
        }
         navService.generateUrl(pageReference)
        .then($A.getCallback(function(url) {
            window.open(url,'_blank');//use _self instead of _blank if you want to redirect in the same page 
        }), 
              $A.getCallback(function(error) {
                  console.log('error: ' + error);
              }));
},

This will open your Account record in a new tab.

|improve this answer|||||
  • I have added all above code in my component and controller but still account are not clickable nor redirectable. – Sangeet Nov 21 '19 at 15:01
  • @Sangeet can you update the code in your initial question with the changes you have made. – samdev Nov 21 '19 at 15:54
  • also the work "onClick" has to have a small "c" like "onclick" – samdev Nov 21 '19 at 16:08
  • Thanks, @samdev Its working fine navigation is working good, Can you just please help me out that how to define url in window.open for opening records of account because i am new in lightning so still i am not able to solve it, I searched on internet also but not get any solution... Please help me out – Sangeet Nov 22 '19 at 5:25
  • @Sangeet you need to create a new question for that and close this one by choosing an answer so that it might help someone else with the same issue. – samdev Nov 22 '19 at 14:53

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