• Akansha Singh 28
  • NEWBIE
  • 0 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 3
    Replies
JAVASCRIPT :

import { LightningElement ,track,wire} from 'lwc';
import getAccountList from '@salesforce/apex/AccountContact.getAccountList';
export default class AccountAndContact extends LightningElement {
@track accounts;
@track error;
@wire(getAccountList)
wiredAccounts({error,data}){
if (data) {
this.accounts = data;
} else if (error) {
this.error = error;
}
}
downloadCSVFile() {  
let listOfAccountsFields = ['Id','Name','Type' ,'Rating' ,'Ownership' , 'Active__c'];
let listOfContactsFields = ['Id','LastName']; 
let rowEnd = '\n';
let listOfContact = [];
this.accounts.forEach(element => {
listOfContact.push(element.Contacts);
});
//console.log('contacts' +JSON.stringify(listOfContact));
let mapOfString = new Map();
listOfContact.forEach(element => {
    let text = listOfContactsFields.join(',')+'\n';
element.forEach(eachElement=>{
    listOfContactsFields.forEach(field =>{
        //console.log('checkfield' +JSON.stringify(field))
        text += '\"'+eachElement[field]+'\"';
        }); 
       });
       text += '\n';
       
       if(mapOfString.has(element.AccountId)){
           mapOfString.set(element.AccountId,mapOfString.get(element.AccountId)+text);
           } 
       else{
           let tempStr = text;
           mapOfString.set(element.AccountId,tempStr);
           }
    //console.log('text' +text);
    
});
const arr = Array.from(mapOfString);
console.log('elementmap-----------' +arr);
let rowData = new Set();
    rowData = Array.from(rowData);
    csvString += listOfAccountsFields.join(',') +rowEnd;
    this.accounts.forEach(element=>{
    listOfAccountsFields.forEach(field=> {
        csvString += '"'+element[field]+'",'
    });
    csvString += '\n';
    csvString += mapOfString.get(element.Id);
})  
console.log('csv----------' +csvString);
let downloadElement = document.createElement('a');
// This  encodeURI encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
downloadElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvString);
downloadElement.target = '_self';
// CSV File Name
downloadElement.download = 'Account Data.csv';
// below statement is required if you are using firefox browser
document.body.appendChild(downloadElement);
// click() Javascript function to download CSV file
downloadElement.click();
document.body.removeChild(downloadElement); 
//console.log(csvString);
}
}

HTML:

<template>
<div class="slds-box slds-theme_default">
    <div class="slds-p-around_medium lgc-bg-inverse">
        <p>Download data as a CSV &nbsp;
            <lightning-button icon-name="utility:download" 
                                label="Download as CSV" 
                                title="Download CSV File"
                                onclick={downloadCSVFile} variant="brand"></lightning-button>
        </p>
    </div>
    <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered">
        <thead>
            <tr>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Account Name">Name</div>
                </th>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Type">Type</div>
                </th>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Rating">Rating</div>
                </th>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Ownership">Ownership</div>
                </th>
                <th class="" scope="col">
                    <div class="slds-truncate" title="Active">Active</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={accounts} for:item="acc">
                <tr key={acc.Id}>
                    <td>{acc.Name}</td>
                    <td>{acc.Type}</td>
                    <td>{acc.Rating}</td>
                    <td>{acc.Ownership}</td>
                    <td>{acc.Active__c}</td>
                </tr>
                <tr key={acc.Id}>
                    <th class="" scope="col">
                        <div class="slds-truncate" title=""></div>
                    </th>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Contact Id">Contact Id</div>
                    </th>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="LastName">LastName</div>
                    </th>
                </tr>
                <template if:true={accounts}>
                    <template for:each={acc.Contacts} for:item="con">
                        <tr key={con.Id}>
                            <td></td>
                            <td>{con.Id}</td>
                            <td>{con.LastName}</td>
                        </tr>
                    </template>
                </template>
            </template> 
        </tbody>
    </table>
</div>   
</template>



CLASS :

public with sharing class AccountContact {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        List<Account> acct= [SELECT Name,Type ,Rating ,Ownership , Active__c,(SELECT Id,LastName,AccountId FROM Contacts)
        FROM Account WHERE Name LIKE'Account%' LIMIT 10];
        return acct;
    }
}

 
apex Class :  public class NewClass {
    public list<account> acct{get;set;}
    public String csvString1{get;set;}
    public String csvString{get;set;}
    public string renderAsExcel{get;set;}
    public NewClass(){
        List<String> listOfAccountsFields = new List<String>{'Id','Name','Type' ,'Rating' ,'Ownership' , 'Active__c'};
            List<String> listOfContactsFields = new List<String>{'Id','LastName'};
                String csvString = String.join(listOfAccountsFields,',')+'\n';
        String csvString1= String.join(listOfContactsFields,',')+'\n';
        acct=[SELECT Id,Name,Type ,Rating ,Ownership , Active__c ,(SELECT Id,lastName from Contacts)
              From Account WHERE Name LIKE'%Account%' LIMIT 10];
        List<Contact> listOfContact = new List<Contact>();
        for(Account accRecord: acct) {
            listOfContact.addAll(accRecord.Contacts);
            //System.debug(listOfContact);
        }
        Map<Id,String> mappingAccAndCon = new Map<Id,String>();
        for(Contact abc: [SELECT AccountId, lastName FROM Contact]) {
            mappingAccAndCon.put(abc.AccountId,abc.lastName);
            system.debug(mappingAccAndCon);
            if(mappingAccAndCon.containsKey(abc.AccountId)){
                mappingAccAndCon.put(abc.AccountId,mappingAccAndCon.get(abc.AccountId)+abc.lastName);   
            }
        }
        for(Account acc:acct){
            for(String fieldName : listOfAccountsFields){
                csvString += '\"'+acc.get(fieldName)+'\",';
            }
            csvString += '\n';
            //csvString += map.get(acc.Id);
            for(String fieldName1 :listOfContactsFields){
                     csvString1 += '\"'+mappingAccAndCon.get(fieldName1)+'\",';
                }
                  csvString1 += '\n';
                system.debug(csvString1);
        }
        renderAsExcel= csvString;
        //system.debug(renderAsExcel);
    }
    public PageReference CSVExporter() {
        PageReference p = new PageReference('/apex/CSVExporter');
        p.setRedirect(true);
        return p;
        
    }
}



vf page 1:<apex:page controller="NewClass" tabStyle="Account">
    <apex:form >
        <apex:pageBlock > 
            <style>
                .myClass{
                color:white !important;
                background: #66b3ff !important;
                }
            </style>
            <Apex:commandButton value="Export as CSV" action="{!CSVExporter}" StyleClass="myClass" />       
        </apex:pageBlock>
    <apex:pageBlock >
            <table border="1">
                <tr>
                    <th>Name</th>
                    <th>Rating</th>
                    <th>Type</th>
                    <th>Active</th>
                    <th>Ownership</th>
                </tr>
                <apex:repeat var="acc" value="{!acct}">
                    <tr>
                        <td>{!acc.Name}</td>
                        <td>{!acc.Rating}</td>
                        <td>{!acc.Type}</td>
                        <td>{!acc.Active__c}</td>
                        <td>{!acc.Ownership}</td></tr>
                    <tr>
                        <th>   </th>
                        <th> Contact Id</th>   
                        <th>LastName</th>
                    </tr>
                    <apex:repeat var="c" value="{!acc.Contacts}">
                        <tr>
                            <td></td>
                            <td>{!c.id}</td>
                            <td>{!c.lastName}</td>
                        </tr>
                    </apex:repeat>
                </apex:repeat> 
            </table>
        </apex:pageBlock>
    </apex:form>
            </apex:page>

vf page 2:
<apex:page controller="NewClass" contentType="text/csv#Test.csv">
    <apex:outputText value="{!renderAsExcel}">
    </apex:outputText>
</apex:page>

please reply asap
apex Class :  public class NewClass {
    public list<account> acct{get;set;}
    public String csvString1{get;set;}
    public String csvString{get;set;}
    public string renderAsExcel{get;set;}
    public NewClass(){
        List<String> listOfAccountsFields = new List<String>{'Id','Name','Type' ,'Rating' ,'Ownership' , 'Active__c'};
            List<String> listOfContactsFields = new List<String>{'Id','LastName'};
                String csvString = String.join(listOfAccountsFields,',')+'\n';
        String csvString1= String.join(listOfContactsFields,',')+'\n';
        acct=[SELECT Id,Name,Type ,Rating ,Ownership , Active__c ,(SELECT Id,lastName from Contacts)
              From Account WHERE Name LIKE'%Account%' LIMIT 10];
        List<Contact> listOfContact = new List<Contact>();
        for(Account accRecord: acct) {
            listOfContact.addAll(accRecord.Contacts);
            //System.debug(listOfContact);
        }
        Map<Id,String> mappingAccAndCon = new Map<Id,String>();
        for(Contact abc: [SELECT AccountId, lastName FROM Contact]) {
            mappingAccAndCon.put(abc.AccountId,abc.lastName);
            system.debug(mappingAccAndCon);
            if(mappingAccAndCon.containsKey(abc.AccountId)){
                mappingAccAndCon.put(abc.AccountId,mappingAccAndCon.get(abc.AccountId)+abc.lastName);   
            }
        }
        for(Account acc:acct){
            for(String fieldName : listOfAccountsFields){
                csvString += '\"'+acc.get(fieldName)+'\",';
            }
            csvString += '\n';
            //csvString += map.get(acc.Id);
            for(String fieldName1 :listOfContactsFields){
                     csvString1 += '\"'+mappingAccAndCon.get(fieldName1)+'\",';
                }
                  csvString1 += '\n';
                system.debug(csvString1);
        }
        renderAsExcel= csvString;
        //system.debug(renderAsExcel);
    }
    public PageReference CSVExporter() {
        PageReference p = new PageReference('/apex/CSVExporter');
        p.setRedirect(true);
        return p;
        
    }
}



vf page 1:<apex:page controller="NewClass" tabStyle="Account">
    <apex:form >
        <apex:pageBlock > 
            <style>
                .myClass{
                color:white !important;
                background: #66b3ff !important;
                }
            </style>
            <Apex:commandButton value="Export as CSV" action="{!CSVExporter}" StyleClass="myClass" />       
        </apex:pageBlock>
    <apex:pageBlock >
            <table border="1">
                <tr>
                    <th>Name</th>
                    <th>Rating</th>
                    <th>Type</th>
                    <th>Active</th>
                    <th>Ownership</th>
                </tr>
                <apex:repeat var="acc" value="{!acct}">
                    <tr>
                        <td>{!acc.Name}</td>
                        <td>{!acc.Rating}</td>
                        <td>{!acc.Type}</td>
                        <td>{!acc.Active__c}</td>
                        <td>{!acc.Ownership}</td></tr>
                    <tr>
                        <th>   </th>
                        <th> Contact Id</th>   
                        <th>LastName</th>
                    </tr>
                    <apex:repeat var="c" value="{!acc.Contacts}">
                        <tr>
                            <td></td>
                            <td>{!c.id}</td>
                            <td>{!c.lastName}</td>
                        </tr>
                    </apex:repeat>
                </apex:repeat> 
            </table>
        </apex:pageBlock>
    </apex:form>
            </apex:page>

vf page 2:
<apex:page controller="NewClass" contentType="text/csv#Test.csv">
    <apex:outputText value="{!renderAsExcel}">
    </apex:outputText>
</apex:page>

please reply asap
What are the basic steps to implement ? when do we need JSON?I know many of you posted code , but please explain me the steps in sequence  in order to implement logic.
Hello,

I am trying to solve the challange of the HTTP and Basic Callout module of Salesforce trailhead and I am having some queries in which you could point to the right direction:

1- The challange asked us to call this URL https://th-apex-http-callout.herokuapp.com/animals/:id in method getAnimalNameById... should that URL be in this form instead of the above https://th-apex-http-callout.herokuapp.com/animals?id ? Where id is a parameter in the URL.

2- When I tried to check the solution of the challange, Salesforce generated that error for me
"Challenge Not yet complete... here's what's wrong: 
Executing the 'getAnimalNameById' method on 'AnimalLocator' failed. Make sure the method exists with the name 'getAnimalNameById', is public and static, accepts an Integer and returns a String."
despite that my class implementation has this method declared as public static String as below in the code snippet:
 
public class AnimalLocator {
	
	public static String getAnimalNameById(Integer id) {
		
		Http http = new Http();
		HttpRequest request = new HttpRequest();
		request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals?id');
		request.setMethod('GET');
		
		HttpResponse response = http.send(request);
		List<Object> animals = NULL;
		String returnValue = NULL;
		
		// if the request was successful, then parse the JSON response
		if (response.getStatusCode() == 200) {
			Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
			animals = (List<Object>) result.get('animals');
			System.debug(animals);
		}
		
		if (animals.size() > 0 && animals != NULL && id < animals.size()) {
			returnValue = (String) animals.get(id);
		}
		
		return returnValue;
	} // end getAnimalNameById method
    
} // end AnimalLocator class

I would appreciate your help in this post.

Thank you,

Sinan