Salesforce Challenge 1 Winner (Aura): Build Opportunity List Component

Challenge 1: Retrieve the list of Opportunity records and display on the page.

Review: Aman Pathak became winner because he added additional features apart from what were asked in the challenge.

Winner:- 2(Aura)

Aman Pathak

My name is Aman, based in Delhi.I did my B.Tech in Electronics Engineering(2017 passout) from UPES,Dehradun.
I have 1.5 years of experience in Salesforce domain, working as a Salesforce Developer in Birlasoft India Ltd.
A bit of nerdy,passionate about Salesforce technology,always trying to learn something new.
Key skils: Salesforce Admin,Apex,Lightning,Lightning Web Component

 

Features Added

  • List of Opportunity Records
  • Download Current list
  • Download All
  • Pagination

SfdcAmplified_Challange.cmp

<aura:component controller="Opportunityhandler" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <!-- aura:attribute  declaration-->
    
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="selectedRowsCount" type="string[]"/>
    
    <!--Pagination attribute-->
    <aura:attribute name="allData" type="List"/>
    <aura:attribute name="currentPageNumber" type="Integer" default="1"/>
    <aura:attribute name="pageSize" type="Integer" default="10"/>
    <aura:attribute name="totalPages" type="Integer" default="0"/>
    <aura:attribute name="pageList" type="List"/>
    <!--Pagination attribute End-->
    <!-- handlers-->
    <aura:handler name="init" value="{!this }" action="{!c.init }"/>
    
    <!--Pagination heavily copied from SFDCFacts Credit: Manish Choudhari-->
    <div style="height: 300px">
        <lightning:card title="SFDCAmplified Challenge Opportunity List with excel download option">
            <lightning:layout multipleRows="true" horizontalAlign="center">
                <lightning:layoutItem padding="around-small" size="12">
                    <lightning:datatable
                                         aura:id="accountDataTable"
                                         columns="{! v.columns }"
                                         data="{! v.data }"
                                         keyField="Id"
                                         onrowselection="{!c.PassToFun}" 
                                         />
                </lightning:layoutItem>
                <lightning:layoutItem padding="around-small" flexibility="auto">
                     <lightning:button name="CSV" label="Download Current List " onclick="{!c.downloadCSV}"/>
                    <lightning:button name="CSV" label="Download All " onclick="{!c.downloadCSVFull}"/>
                    <lightning:button label="First" iconName="utility:left" iconPosition="left"
                                      onclick="{!c.onFirst}" disabled="{! v.currentPageNumber == 1}"/>
                    <lightning:button iconName="utility:chevronleft" iconPosition="left"
                                      onclick="{!c.onPrev}" disabled="{! v.currentPageNumber == 1}"/>
                    <span class="slds-p-horizontal_x-small">
                        <a onclick="{!c.processMe}" name="1" 
                           class="{! (v.currentPageNumber == 1) ? 'selected' : ''}">1</a>
                    </span>
                    <span class="slds-p-horizontal_xxx-small">
                        <a>...</a>
                    </span>
                    
                    <aura:iteration items="{!v.pageList}" var="item">
                        <span class="slds-p-horizontal_x-small">
                            <a onclick="{!c.processMe}" name="{!item}"
                               class="{! (v.currentPageNumber == item) ? 'selected' : ''}">{!item}</a>
                        </span>
                    </aura:iteration>
                    
                    <span class="slds-p-horizontal_xxx-small">
                        <a>...</a>
                    </span>
                    <span class="slds-p-horizontal_x-small">
                        <a onclick="{!c.processMe}" name="{!v.totalPages}"
                           class="{! (v.currentPageNumber == v.totalPages) ? 'selected' : ''}">{!v.totalPages}</a>
                    </span>
                    <lightning:button iconName="utility:chevronright" iconPosition="right" 
                                      disabled="{! v.currentPageNumber == v.totalPages}" onclick="{!c.onNext}"/>
                    <lightning:button label="Last" iconName="utility:right" iconPosition="right" 
                                      disabled="{! v.currentPageNumber == v.totalPages}" onclick="{!c.onLast}"/>
                </lightning:layoutItem>
            </lightning:layout>
        </lightning:card>
    </div>
</aura:component>

SFDCAmplified_ChallengeController

({
    init: function (cmp, event, helper) {
        //var pageSize = component.get("v.pageSize");
        cmp.set('v.columns', [
            {label: 'Opportunity name', fieldName: 'Name', type: 'text', editable: true, typeAttributes: { required: true }},
            {
                label: 'Close date', fieldName: 'CloseDate', type: 'date', editable: true,
                typeAttributes: {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit'
                }
            },
            {label: 'Amount', fieldName: 'Amount', type: 'currency', typeAttributes: { currencyCode: 'USD'}, editable: true, typeAttributes: { required: true } }
        ]);
       helper.getOpp(cmp,event,helper);
    },
    PassToFun :function (cmp, event, helper) {
        var selectedRows = event.getParam('selectedRows');
        cmp.set('v.selectedRowsCount', selectedRows)
        console.log(cmp.get('v.selectedRowsCount'));
    },
     downloadCSV : function(component, event, helper,fileTitle) {
        var stockData = component.get("v.selectedRowsCount");
         if(stockData.length == 0){
              alert('Select atleast one opportunity from the list')
             return;}
        else{
        var csv = helper.convertArrayOfObjectsToCSV(component,stockData);
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'export'+'.csv'; 
        hiddenElement.click();
         }
    }, 
         downloadCSVFull : function(component, event, helper,fileTitle) {
        var stockData = component.get("v.allData");
         if(stockData.length == 0){
              alert('Select atleast one opportunity from the list')
             return;}
        else{
        var csv = helper.convertArrayOfObjectsToCSV(component,stockData);
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'export'+'.csv'; 
        hiddenElement.click();
         }
    },
    onNext : function(component, event, helper) {        
        var pageNumber = component.get("v.currentPageNumber");
        component.set("v.currentPageNumber", pageNumber+1);
        helper.buildData(component, helper);
    },
    
    onPrev : function(component, event, helper) {        
        var pageNumber = component.get("v.currentPageNumber");
        component.set("v.currentPageNumber", pageNumber-1);
        helper.buildData(component, helper);
    },
    
    processMe : function(component, event, helper) {
        component.set("v.currentPageNumber", parseInt(event.target.name));
        helper.buildData(component, helper);
    },
    
    onFirst : function(component, event, helper) {        
        component.set("v.currentPageNumber", 1);
        helper.buildData(component, helper);
    },
    
    onLast : function(component, event, helper) {        
        component.set("v.currentPageNumber", component.get("v.totalPages"));
        helper.buildData(component, helper);
    },
  
})

SfdcAmplified_ChallangeHelper

({
    getOpp : function(component,event,helper) {
        var action= component.get('c.getOpportunityList');
        //action.setStorable();
        action.setCallback(this,function(response)
                           {
                               var state =response.getState();
                               if(state==="SUCCESS")
                               {
                                   var result=response.getReturnValue();
                                   //component.set('v.data',result);
                                   //alert('result '+result);
                                   component.set("v.totalPages", Math.ceil(response.getReturnValue().length/component.get("v.pageSize")));
                                   component.set("v.allData", response.getReturnValue());
                                   component.set("v.currentPageNumber",1);
                                   helper.buildData(component,helper);
                                   
                               }
                               else
                               {
                                   console.log('Error');
                               }
                           });
        $A.enqueueAction(action);
    },
    convertArrayOfObjectsToCSV : function(component,objectRecords){
        // declare variables
        var csvStringResult, counter, keys, columnDivider, lineDivider,parentKey;
        
        // check if "objectRecords" parameter is null, then return from function
        if (objectRecords == null || !objectRecords.length) {
            return null;
        }
        // store ,[comma] in columnDivider variabel for sparate CSV values and 
        // for start next line use '\n' [new line] in lineDivider varaible  
        columnDivider = ',';
        lineDivider =  '\n';
        
        // in the keys valirable store fields API Names as a key 
        // this labels use in CSV file header  
        keys = ['Name','CloseDate','Amount' ];
        csvStringResult = '';
        csvStringResult += keys.join(columnDivider);
        csvStringResult += lineDivider;
        
        for(var i=0; i < objectRecords.length; i++){   
            counter = 0;
            
            for(var sTempkey in keys) {
                var skey = keys[sTempkey] ; 
                // add , [comma] after every String value,. [except first]
                if(counter > 0){ 
                    csvStringResult += columnDivider; 
                }   
                
                csvStringResult += '"'+ objectRecords[i][skey]+'"'; 
                counter++;
            } // inner for loop close     
            csvStringResult += lineDivider;
        }// outer main for loop close 
        
        // return the CSV formate String 
        return csvStringResult;        
    },
 buildData : function(component,helper) {
        var data = [];
        var pageNumber = component.get("v.currentPageNumber");
        var pageSize = component.get("v.pageSize");
        var allData = component.get("v.allData");
        var x = (pageNumber-1)*pageSize;
        
        //creating data-table data
        for(; x<=(pageNumber)*pageSize; x++){
            if(allData[x]){
            	data.push(allData[x]);
            }
        }
        component.set("v.data", data);
        helper.generatePageList(component, pageNumber);
    },
    
    /*
     * this function generate page list
     * */
    generatePageList : function(component, pageNumber){
        pageNumber = parseInt(pageNumber);
        var pageList = [];
        var totalPages = component.get("v.totalPages");
        if(totalPages > 1){
            if(totalPages <= 10){
                var counter = 2;
                for(; counter < (totalPages); counter++){
                    pageList.push(counter);
                } 
            } else{
                if(pageNumber < 5){
                    pageList.push(2, 3, 4, 5, 6);
                } else{
                    if(pageNumber>(totalPages-5)){
                        pageList.push(totalPages-5, totalPages-4, totalPages-3, totalPages-2, totalPages-1);
                    } else{
                        pageList.push(pageNumber-2, pageNumber-1, pageNumber, pageNumber+1, pageNumber+2);
                    }
                }
            }
        }
        component.set("v.pageList", pageList);
    },
   
 })

sfdcAmplifiedChallange.app

<aura:application extends="force:slds">
    <c:SFDCAmplified_Challenge/>	
</aura:application>

OpportunityHandler

public class Opportunityhandler {
   
    @auraenabled
    public static List<opportunity> getOpportunityList()
    {
        return [select Name,closeDate,Amount from opportunity];
    }
}

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes