0

Account Details

Requirement: There is a button "Export Today " which is used to export account records in the form of csv in lightning component(Account_Detail_Component).In the helper ,we have "convertArrayOfObjectsToCSV" function which is used to convert object records into csv. I am able to display account fields values i.e 'Name','AccountNumber','Id' in csv. But I am not able to display parent account field values i.e parent account Number.You can find apex controller"CsvDownloadCtrller" which is returning account fields values and parent account Number.You can find the output of CSV File which is displaying account Records and parent account Number as [object][object] with the below helper code.

enter image description here

You can this below code commented in helper because It is displaying account fields along undefined values and parent record as [object][object] correct parent accountNumber

if(csvStringResult.includes("Parent")){
    for(var sTemp in parentKey){
        var orgnKey = parentKey[sTemp];     
        csvStringResult += '"'+ objectRecords[i][skey][orgnKey]+'"'; 
    }
} 

enter image description here

Could any one please correct my code to display proper account records and parent account records

Apex Controller:

public class CsvDownloadCtrller {
    @AuraEnabled
    public static List<Account> getAccounts(){
       return [Select id,name,accountnumber,parent.accountnumber from Account where parent.id!=null and parent.accountnumber!=null];
    }
}

Component:

<aura:component  controller="CsvDownloadCtrller" implements="force:appHostable">
    <aura:attribute name="AcctLst" type="Account[]"></aura:attribute>
    <aura:handler name="init" value="{!this}" action="{!c.loadAcctRcrds}"/>
    <aura:attribute name="AcctRcrdTypeLst" type="String[]"></aura:attribute>
    <aura:attribute name="selectedLookUpRecord" type="sobject" default="{}"/>
    <div class="slds-box slds-box">
  <article class="slds-card">
  <div class="slds-card__header slds-grid">
    <header class="slds-media slds-media_center slds-has-flexi-truncate">

      <div class="slds-media__body">
        <h2 class="slds-card__header-title">
          <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
            <span class="slds-text-heading_small">Account List View</span>
          </a>
        </h2>
      </div>

      <div class="slds-no-flex">
        <button class="slds-button slds-button_brand" onclick="{!c.exprtTodysRecrds}">Export Today</button>
        <button class="slds-button slds-button_brand">Export Weekly</button>  
      </div>
    </header>
  </div>
</article>

 <article class="slds-card">
  <div class="slds-card__header slds-grid">
    <header class="slds-media slds-media_center slds-has-flexi-truncate">

      <div class="slds-media__body">
        <h2 class="slds-card__header-title">
          <a href="javascript:void(0);" class="slds-card__header-link slds-truncate" title="Accounts">
            <span class="slds-text-heading_small">Search Accounts</span>
          </a>
        </h2>
      </div>

    </header>
  </div>
</article>
<div class="slds-form slds-form_compound">
    <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
<lightning:select name="select1" label="Account Type" required="true">
        <aura:iteration items="{!v.AcctRcrdTypeLst}" var="acct">
            <option text="{!acct}"></option>    
        </aura:iteration>
    </lightning:select>
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Parent Account Number" name="ParentAccountNumber"  />
</div>
</div>
</div>
</fieldset>
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">
<div class="slds-form-element slds-size_1-of-2">
</div>
<div class="slds-form-element slds-size_1-of-2">
<lightning:input aura:id="field" label="Account Number" name="AccountNumber"  />   
</div>    
</div>
</div>
</fieldset>
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">
    <lightning:textarea name="input1" label="Description" />    
</div>
<div class="slds-form-element slds-size_1-of-2">
<c:customLookup objectAPIName="account"  label="Account Number" selectedRecord="{!v.selectedLookUpRecord}"/>
</div>    
</div>
</div>
</fieldset> 
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">        
</div>
<div class="slds-form-element slds-size_1-of-2">    
</div>    
</div>
</div>
</fieldset>
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">        
</div>
<div class="slds-form-element slds-size_1-of-2">    
</div>    
</div>
</div>
</fieldset>          
 <fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">

</div>
<div class="slds-form-element slds-size_1-of-2"> 
    <lightning:input type="date" name="input1" label="From Date" /> 
</div>    
</div>
</div>
</fieldset>   
<fieldset class="slds-form-element">
<div class="slds-form-element__group">
<div class="slds-form-element__row">    
<div class="slds-form-element slds-size_1-of-2">        
</div>
<div class="slds-form-element slds-size_1-of-2"> 
    <lightning:input type="date" name="input1" label="To Date" /> 
</div>    
</div>
</div>
</fieldset>  
</div>

<div class="slds-no-flex slds-align_absolute-center slds-m-top_xx-large">
        <button class="slds-button slds-button_brand" style="width:100px">Search</button>
        <button class="slds-button slds-button_brand" style="width:100px">Clear</button>  
      </div> 
</div> 
</aura:component>

Controller:

({
    loadAcctRcrds:function(component,event,helper){

       var action = component.get("c.getAccounts");
        action.setCallback(this,function(response){
        var state = response.getState();



            if(state == "SUCCESS"){

                component.set("v.AcctLst",response.getReturnValue());

            }
            else{
                alert('failed');

            }
        });
        $A.enqueueAction(action);      

    },

    exprtTodysRecrds : function(component, event, helper) {
         var stockData = component.get("v.AcctLst") 
         var csv = helper.convertArrayOfObjectsToCSV(component,stockData);
          if (csv == null){return;} 

        // ####--code for create a temp. <a> html tag [link tag] for download the CSV file--####     
         var hiddenElement = document.createElement('a');
          hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
          hiddenElement.target = '_self'; // 
          hiddenElement.download = 'ExportData.csv';  // CSV file Name* you can change it.[only name not .csv] 
          document.body.appendChild(hiddenElement); // Required for FireFox browser
          hiddenElement.click(); // using click() js function to download csv file


    }
})

Helper:

({

    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','AccountNumber','Id','Parent' ];
        parentKey=['AccountNumber'];

        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] ; 

                /* if(skey=='Parent'){
                     for(var pTempkey in parentKey){
                         csvStringResult += '"'+ objectRecords[i][skey][pTempkey]+'"';                       

                     }  


                 }*/


              // add , [comma] after every String value,. [except first]
                  if(counter > 0){ 
                      csvStringResult += columnDivider; 
                   }   

               csvStringResult += '"'+ objectRecords[i][skey]+'"'; 

                 /*if(csvStringResult.includes("Parent")){
                     for(var sTemp in parentKey){
                        var orgnKey = parentKey[sTemp];     
                        csvStringResult += '"'+ objectRecords[i][skey][orgnKey]+'"'; 

                     }

                 }*/ 



               counter++;

             } // inner for loop close     
             csvStringResult += lineDivider;
          }// outer main for loop close 

       // return the CSV formate String 
        return csvStringResult;        
    },

})

1 Answer 1

1

Basically the problem you're having is that you are missing an else statement. Essentially you're adding both the parent and child field to the same column. The [object] part is from the child and the 23456 is from the parent (also notice your other columns have undefined at the end of them). If you use an else statement you can probably fix your issue:

if(skey=='Parent'){
    for(var pTempkey in parentKey){
        csvStringResult += '"'+ objectRecords[i][skey][pTempkey]+'"';                       
    }
} else { // This one right here
    csvStringResult += '"'+ objectRecords[i][skey]+'"'; 
}

While this is probably enough to fix your issue, you are going to run into another problem if you add more than 1 key to the parent keys array. All of your parent fields will be put into the same column (or columns with no headers). The following changes things up a little bit so that you can have any number of parent columns in your parentKeys array and it will still work.

({
    convertArrayOfObjectsToCSV : function(component,objectRecords){
        var csvStringResult, counter, keys, columnDivider, lineDivider,parentKey;

        if (objectRecords == null || !objectRecords.length) {
            return null;
        }

        columnDivider = ',';
        lineDivider =  '\n';

        keys = ['Name','AccountNumber','Id']; // Remove parent
        parentKeys=['AccountNumber', 'Name', 'Id']; // Add what ever fields you want

        csvStringResult = '';
        csvStringResult += keys.join(columnDivider);

        counter = 0;

        // Add parent column headers
        // We need to add "Parent." before the keys for clarity
        for (var parentKey in parentKeys) {
            if (couner > 0) {
                csvString += columnDivider;
            }

            csvStringResult += 'Parent.' + parentKey;
            counter++;
        }

        csvStringResult += lineDivider;

        for(var i=0; i < objectRecords.length; i++){
            counter = 0;

            for(var sTempkey in keys) {
                if(counter > 0){ 
                    csvStringResult += columnDivider; 
                }

                csvStringResult += '"'+ objectRecords[i][sTempkey]+'"'; 

               counter++;
            }

            counter = 0;

            // Repeat the same process for the parent fields
            for(var sTempkey in parentKeys) {
                if(counter > 0){ 
                    csvStringResult += columnDivider; 
                }

                csvStringResult += '"'+ objectRecords[i]['parent'][sTempkey]+'"';

               counter++;
            }

            csvStringResult += lineDivider;
        }

       return csvStringResult;        
    },

})

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .