Thursday 3 August 2023

Lookup component in Salesforce Lightning

 Lookup component in Salesforce Lightning




Following source code is for Contact Lookup component.

<aura:component controller="ContactLookupController" >
   
    <aura:attribute name="listOfSearchRecords" type="object[]" description="Use,for store the list of search records which returns from apex class"/>
    <aura:attribute name="SearchKeyWord" type="string"/>
    <aura:attribute name="Message" type="String" default="Search Result.."/>
    <aura:attribute name="selectedRecordName" type="string"/>
    <aura:attribute name="selectedRecordId" type="string"/>
  
    <aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
    <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
    
  
    <div class="">
        <div aura:id="searchRes" class="slds-form-element slds-lookup slds-is-close" data-select="single">
            <!--<label class="slds-form-element__label" for="lookup-348"> Account Name </label>-->
            <!--This part is for display search bar for lookup-->  
            <div class="slds-form-element__control">
                <div class="slds-input-has-icon slds-input-has-icon--right">
                    <lightning:icon aura:id="SearchID" class="slds-input__icon slds-show" iconName="utility:search" size="x-small" alternativeText="icon" />               
                    <!-- This markup is for when an record is selected -->
                    <div aura:id="lookup-pill" class="slds-pill-container slds-hide">
                        <span class="slds-pill">
                            <span class="slds-pill__label">
                                {!v.selectedRecordName}
                            </span>
                            <button class="slds-button slds-button--icon slds-pill__remove" onclick="{!c.clear}">
                                <lightning:icon aura:id="RemoveID" class="slds-input__icon CloseIcn" iconName="utility:close" size="x-small" alternativeText="icon" />
                                <span class="slds-assistive-text">Remove</span>
                            </button>
                        </span>
                    </div>
                    <div aura:id="lookupField" class="slds-show">
                        <ui:inputText  updateOn="keyup" keyup="{!c.keyPressController}" class="slds-lookup__search-input slds-input " value="{!v.SearchKeyWord}" placeholder="search.."/>
                    </div>   
                </div>
            </div>
            <!--This part is for Display typehead lookup result List-->  
            <div class="slds-lookup__menu slds" id="lookup-348">
                <div class="slds-lookup__item--label slds-text-body--small">{!v.Message}</div>
                <center> <ui:spinner aura:id="spinner"/> </center>
                <ul class="slds-lookup__list" role="listbox">
                    <aura:iteration items="{!v.listOfSearchRecords}" var="singleRec">
                        <li role="presentation">
                            <span class="slds-lookup__item-action slds-media slds-media--center" id="lookup-option-350" role="option">
                                <div class="slds-media__body">
                                    <div class="slds-input-has-icon slds-input-has-icon--right">
                                        <!--Icon of Account -->
                                        <div class="slds-lookup__result-text" title="{!singleRec.Name}" >
                                            <a data-record="{!singleRec.Id+'#'+singleRec.Name}" onclick="{!c.selectAccount}">
                                                {!singleRec.Name}                                       
                                            </a>
                                        </div>
                                    </div>
                                </div>    
                            </span>
                        </li>                        
                    </aura:iteration>
                </ul>
            </div>
        </div>
    </div>
</aura:component>


Following source code is for ContactLookupController.js component.

({
    
    keyPressController : function(component, event, helper) {
        // get the search Input keyword   
        var getInputkeyWord = component.get("v.SearchKeyWord");
        // check if getInputKeyWord size id more then 0 then open the lookup result List and 
        // call the helper 
        // else close the lookup result List part.   
        if( getInputkeyWord.length > 0 ){
            var forOpen = component.find("searchRes");
            $A.util.addClass(forOpen, 'slds-is-open');
            $A.util.removeClass(forOpen, 'slds-is-close');
            helper.searchHelper(component,event,getInputkeyWord);
        }
        else{  
            component.set("v.listOfSearchRecords", null ); 
            var forclose = component.find("searchRes");
            $A.util.addClass(forclose, 'slds-is-close');
            $A.util.removeClass(forclose, 'slds-is-open');
        }
        
    },
    
    // function for clear the Record Selaction 
    clear :function(component,event,heplper){
        
        var pillTarget = component.find("lookup-pill");
        var lookUpTarget = component.find("lookupField"); 
        
        $A.util.addClass(pillTarget, 'slds-hide');
        $A.util.removeClass(pillTarget, 'slds-show');
        
        $A.util.addClass(lookUpTarget, 'slds-show');
        $A.util.removeClass(lookUpTarget, 'slds-hide');
        
        component.set("v.SearchKeyWord",null);
        component.set("v.listOfSearchRecords", null );
        
        $A.util.removeClass(component.find("SearchID"),'slds-hide')
        $A.util.addClass(component.find("SearchID"),'slds-show')
        
        $A.util.addClass(component.find("RemoveID"),'slds-hide')
        $A.util.removeClass(component.find("RemoveID"),'slds-show')
        
    },
        
    // automatically call when the component is done waiting for a response to a server request.  
    hideSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : false });
        evt.fire();    
    },
    // automatically call when the component is waiting for a response to a server request.
    showSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : true });
        evt.fire();    
    },
    
    selectAccount : function(component, event, helper){       
        var selectedItem = event.currentTarget;
        var data = selectedItem.dataset.record;
        
        var arr = data.split('#');
        console.log('Id='+arr[0]);
        console.log('Name='+arr[1]);
        
        component.set("v.selectedRecordId" , arr[0]);
        component.set("v.selectedRecordName" , arr[1]);         
        
        var forclose = component.find("lookup-pill");
        $A.util.addClass(forclose, 'slds-show');
        $A.util.removeClass(forclose, 'slds-hide');            
        var forclose = component.find("searchRes");
        $A.util.addClass(forclose, 'slds-is-close');
        $A.util.removeClass(forclose, 'slds-is-open');       
        var lookUpTarget = component.find("lookupField");
        $A.util.addClass(lookUpTarget, 'slds-hide');
        $A.util.removeClass(lookUpTarget, 'slds-show'); 
        
        $A.util.addClass(component.find("SearchID"),'slds-hide')
        $A.util.removeClass(component.find("SearchID"),'slds-show')
        
        $A.util.addClass(component.find("RemoveID"),'slds-show')
        $A.util.removeClass(component.find("RemoveID"),'slds-hide')       
    },
    
})


Following source code is for ContactLookupHelper.js component.

({
    searchHelper : function(component,event,getInputkeyWord) {
        var action = component.get("c.fetchContact");
        action.setParams({
            'searchKeyWord': getInputkeyWord
        }); 
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log('SUCCESS ====');
                var storeResponse = response.getReturnValue();
                 console.log('storeResponse ===='+storeResponse);
                if (storeResponse.length == 0) {
                    component.set("v.Message", 'No Result Found...');
                } else {
                    component.set("v.Message", 'Result...');
                }                
                component.set("v.listOfSearchRecords", storeResponse);
            }
            
        });
        $A.enqueueAction(action);    
    },
})

Following source code is for ContactLookup.css component.

.THIS .slds-pill{width: 100%;
    padding: 8px 10px;
}
.THIS .CloseIcn{
    position: absolute;
    top: 7px;
    right: 0px;
}


Following source code is for ContactLookupController apex class.

public class ContactLookupController {

    @AuraEnabled
    public static List <Contact> fetchContact(String searchKeyWord) {
        system.debug('## searchKeyWord ==>'+searchKeyWord);
        String searchKey = searchKeyWord + '%';
        List <Contact> returnList = new List <Contact> ();
        List <Contact> lstOfContact = [select id, Name from Contact where Name LIKE: searchKey ];
          system.debug('## lstOfContact ==>'+lstOfContact.size());
        for (Contact acc: lstOfContact) {
            returnList.add(acc);
        }
        return returnList;
    }
}




Wednesday 7 June 2023

Get selected row id in aura component

 

Get selected row id in aura component




Below is aura:iteration example in aura componnet 

step 1: Define the data-record attribute and on click event

<aura:iteration items="{!v.ShowRecords}" var="acc">

<div class="slds-grid slds-wrap mainsearchBox">

<div class="imgDiv slds-col slds-size_2-of-12 slds-small-size_2-of-12 slds-medium-size_2-of-12" style="text-align:center;">

<div class="holder">                      

<div data-record="{!acc.Id}" onclick="{!c.goToProfile}"><a><img src="{!acc.Logo_URL}" class="logoImg" /> </a></div>        

</div>

</div>                             

</div>

</aura: iteration>



step 2:  Add the click event in controller.js

goToProfile : function(component, event, helper) {

console.log('goToProfile ------');

var selectedItem = event.currentTarget;

  

var Id = selectedItem.dataset.record;

console.log('Id='+Id);



Tuesday 6 June 2023

Increase quick action window width

 

Increase size (width) of Lightning Web Component Quick Action Modal Popup Salesforce



<aura:component controller="PaymentCalculatorController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <aura:attribute name="recordId" type="String" />

<aura:attribute name="actionWidth" type="string" default="75"/>


 <aura:html tag="style">             

        .slds-modal__container{        

        width: 100% !important;

        max-width: {!v.actionWidth}rem !important; 

        }      

        

        .slds-modal__footer {

        display: none;

        }

    </aura:html>





</aura: component >

Tuesday 30 May 2023

Send email using guest user by apex code

Sending Email from Guest User Profile- Email No Receiving Email 



Send email using guest user




public pageReference generatePDF() {    

        if(caseId != '') {

            Case cs = [select Id,CaseNumber,Quote_Number__c from Case where Id=:caseId LIMIT 1];      

            pageReference pdfPage = Page.EnceliumForm;

            blob pdfBody;

            if(Test.isRunningTest()) { 

              pdfBody = blob.valueOf('Unit.Test');

            } else {

                pdfBody = pdfPage.getContentAsPdf(); 

            }       

            system.debug('in method--------->>'+caseId+cs);

            system.debug('pdfFile===>'+pdfBody);

            attachment pdfFile = new attachment();

            pdfFile.isPrivate  = false;

            pdfFile.body       = pdfBody;

            pdfFile.parentId   = cs.Id; // '5003B000005oRIx';

            pdfFile.Name       = 'Encelium Request form.pdf';        

            insert pdfFile; 

            system.debug('## pdfFile===>'+pdfFile);

            if(string.isNotBlank(ecContactEmail)) {

                system.debug('## ecContactEmail===>'+ecContactEmail);                

                OrgWideEmailAddress owea = new OrgWideEmailAddress();

                owea = [SELECT Id, Address, DisplayName FROM 

                        OrgWideEmailAddress WHERE displayname='Legrand CRM Support Team' limit 1];                                                

                string conEmail = ecContactEmail;

                Messaging.EmailFileAttachment att = new Messaging.EmailFileAttachment();

                att.setBody(pdfBody);

                att.setContentType('application/pdf');

                att.setFileName('attachment.pdf');

                Messaging.SingleEmailMessage mess = new Messaging.SingleEmailMessage();

                mess.setSubject('Encelium Request Form:'+' Your Case Number: '+ cs.CaseNumber);

                mess.setToAddresses(new String[]{conEmail}); 

                

                mess.setHtmlBody('Please find attached self-signed Encelium Request Form. <br/><br/> Please do not reply to this mail');

                mess.setFileAttachments(new Messaging.EmailFileAttachment[]{att});

                mess.setSaveAsActivity(false);

                mess.setOrgWideEmailAddressId(owea.id);

              //Messaging.sendEmail(new Messaging.Email[]{mess});

                system.debug('## End===>');

                

                try{

                    List<Messaging.SendEmailResult> results =   Messaging.sendEmail(new Messaging.Email[]{mess});

                    if(results[0].success){

                         system.debug('## success===>');

                    }else{

                        system.debug('## Fail===>');

                    }

                } catch(Exception ex){

                    system.debug('## Exception===>'+ex.getMessage() +' LN ='+ex.getLineNumber());

                }

                

                

            }

        }

        return new pagereference('http://www.Legrand.us').setRedirect(true);

    }

Wednesday 22 February 2023

How to detect browser in lightning component

 

How to detect browser in lightning component


This example shows usage of the $Browser global value provider.

In Lightning component 

<aura:component> {!$Browser.isTablet} {!$Browser.isPhone} {!$Browser.isAndroid} {!$Browser.formFactor} </aura: component>

In a client-side controller

({ checkBrowser: function(component) { var device = $A.get("$Browser.formFactor"); alert("You are using a " + device); } })





Thursday 19 January 2023

Get URL parameters in Lightning Components

 You can get lightning parameter in two way : 

1)  

lightning:isUrlAddressable Interface : Get URL parameters in Lightning Components


We can fetch URL param by using "{!v.PageReference.state.parameterName}" where parameterName is URL parameter name.


<aura:component  implements="lightning:isUrlAddressable,force:appHostable" access="global">
    <aura:attribute name="urlParam" type="string"/>
    <div class="slds-card">
    If you implements "lightning:isUrlAddressable" interface, then by 
        using v.pageReference,you can get URL params.
    <div class="slds-box">  
        Account Name is :  <b>{!v.pageReference.state.accname}</b>
        </div>
    </div> 
</aura:component>

"/lightning/n/tabName?accname=Naresh Thakur"

Output is : 
Account Name is : Naresh Thakur



2) You can write code in js component 
For Ex 

doInit : function(component, event, helper) {       
         var sPageURL = decodeURIComponent(window.location.search.substring(1));
         var sURLVariables = sPageURL.split('&');
         var sParameterName;
         for (var i = 0; i < sURLVariables.length; i++) {
             sParameterName = sURLVariables[i].split('=');             
             if (sParameterName[0] === 'conId') {
                 component.set('v.tempConId',sParameterName[1]);
             }
         }
         
        // Other code goes here
    },

Call it 
https://YourURL/Pagename?conId = aio000000000ADSuiq