• RarLopz
  • NEWBIE
  • 180 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 28
    Questions
  • 42
    Replies
I want to create a report that would give me all Contacts that are related to Accounts where there are no activites associated to these Contacts, neither are there no current and past activities associated with the related accounts. 

So far, this is what i have. (see screen shot)
Am i in the right direction? 

User-added image
//Following is string i have in custom setting

Ay|a*s'}+ie'\ }5jI2v[ m);pIB}mnO<qT'?/Abzm*Z+}1#@!l$MdsljF$)b|YZ

//I know I can escape the reserved characters in the string by appeending with \

String mystring =  'Ay|a*s'}+ie<b>\</b>'<b>\</b>\ }5jI2v[ m);pIB}mnO<qT<b>\</b>'?/Abzm*Z+}1#@!l$MdsljF$)b|YZ';

system.debug(mystring);

output exactly as original string: Ay|a*s'}+ie'\ }5jI2v[ m);pIB}mnO<qT'?/Abzm*Z+}1#@!l$MdsljF$)b|YZ

However I don't know how to escape the reserved characters when the string is stored in the custom setting. Everything i have tried has failed.
 
CustomSetting__c cs = CustomSetting__c.getInstance();
 
string afterescapingreservedcharacters = cs.SecretAccessKey__c.unescapeJava();
 
system.debug('After escaping reserved characters:  ' +afterescapingreservedcharacters );


After escaping reserved characters:  Ay|a*s'}+ie' }5jI2v[ m);pIB}mnO<qT'?/Abzm*Z+}1#@!l$MdsljF$)b|YZ

Basically in the out put above the \ is missing from the original string. instead of escaping it, the unEscapeJava funtion removed it.

What do i have to do to escape the reserved characters and get the string as it is in Custom Setting ?
i am trying to display the time from Apex controller to Lightning component. 
is it possible to directly get Datetime.now () in the js controller and display it on the component? 



({	
	ctr : function(cmp, event, helper) {
        var temp = [];
       
        var action = cmp.get("c.getGraph");
        action.setParams({
        	"accountid": cmp.get("v.recordId")
       	});
        action.setCallback(this, function(response){
            if(response.getState() === 'SUCCESS' && response.getReturnValue()){
                temp = response.getReturnValue();
                helper.createGraph(cmp, temp);
            }
        });      
          
       $A.enqueueAction(action);
      
	},
    
    cancelAction: function(component, event, helper) {
   		$A.get("e.force:closeQuickAction").fire();
	}
})



 
Can some one plese assist? 

If you look at my wrapper class, there is an inner class EcPerformanceRecordList .I have declared a list<EcPerformanceRecordList>  for getting and setting values between controller and UI

When i try to create a map so that I have a list of EcPerformaceRecordList per User, I get an error when I declare the map as map<String,<list<EcPerformanceRecordList>>

How can i declare a Map and loop through this map so that I can count how many apps have been submitted per user.
e.g 
    UserID  Total  EC(Yes)     Date
    user1   12      4          06/12/2019
    user1   13      13         06/13/2019
    user2   35      24         06/18/2019
    user3   23      31         07/02/2019    
    user1   17       2          07/10/2019
    user3   12       3          07/10/2019

I am trying something like this 
Map<userid, list<ecRecordList>> mapname = newMap<userid, list<ecRecordList>> 

mapname.put(user1, <{user1 12 4 06/12/2019}, {user1 13 13 06/13/2019},{user1 17 2 07/10/2019} )

mapname.put(user2, <{ user2 35 24 06/18/2019}, {user1 13 13 06/13/2019},{user1 17 2 07/10/2019} ) and so on.

then for each user, i want to loop through the list and calculate the totals. 
 

Here's snippet of my code for reference.  


public with sharing class MyController {

		public list<MyWrapper> wrapper {get;set;}
    	public integer appTotal {get;set;} 
    	public integer mtdappTotal {get;set;} 
    	public integer previousmonthappTotal {get;set;} 
    	public integer idlplusmtdTotal {get;set;}
    	public integer idlpluspreviousmonthTotal {get;set;}
    	public integer caTotal {get;set;}
    	public integer ecmtdTotal {get;set;}
    	public integer ecpreviousmonthTotal {get;set;}
    	public integer ecEligibleYesMTDTotal {get;set;}
    	public integer ecEligibleYesPreviosMonthTotal {get;set;}
    	public set<String> userid {get;set;}
		public Map<String,list<EcPerformanceRecordList>> ecperuserMap {get;set;}
    
    	
    	@AuraEnabled(cacheable=true)
		public void getdeserialize() {
		
			try{
                string jsonresponse = 'SOME STRING'
			   
			 	
                wrapper = (list<MyWrapper>) JSON.deserialize(jsonresponse, list<MyWrapper>.class);
			 	
                
                // call the method that aggregates the MonthToDate app count, and PreviousMonth app count per user 
                getTotalECBookedByUser(wrapper);
               
              
		     	
			} catch (Exception e){
				system.debug('Error---->' +  e.getLineNumber() + e.getMessage());
				
			}
    	}
    
    	
    
    // This method calclates the total EC Booked current month and previous month by each user 
    public integer getTotalECBookedByUser(list<MyWrapper> wrapper) {
        	     
        
		Map<String,list<EcPerformanceRecordList>> ecperuserMap = new Map<String,list<EcPerformanceRecordList>>();  
		for(MyWrapper jw: wrapper){
            
            jw.ecpreviousmonthTotal=0;
			jw.ecmtdTotal = 0;   
        	// create a map of submitUserID and ECSubmittedRecordList 
			Map<String,list<EcPerformanceRecordList>> ecperuserMap = new Map<String,list<EcPerformanceRecordList>>();  
        	 
        	for (MyWrapper.EcPerformanceRecordList ec : jw.ecPerformanceRecordList) {
            	
				if(ecperuserMap.containsKey(ec.submitUserID)){
				
					 ecperuserMap.get(ec.submitUserID).add(ec);

				}else {
				
					ecperuserMap.put(ec.submitUserID,ec);
				}
				          	  
            }
        }
		
		// loop through the map ecperuserMap and count the total apps submitted by each user this month and previous month 
		
		
        
        return ecpreviousmonthTotal;
        return ecmtdTotal;
	
    }
    
  
     
}




------------------------Wrapper Class ------------------


public class MyWrapper {
@AuraEnabled	
    public List<CaPerformanceRecordList> caPerformanceRecordList{get;set;}
    public List<EcPerformanceRecordList> ecPerformanceRecordList{get;set;}
    public Map<String,List<EcPerformanceRecordList>> ecPerUser {get;set;}
    public integer appTotal{get;set;}
    public integer mtdappTotal {get;set;} 
    public integer previousmonthappTotal {get;set;} 
    public integer idlplusmtdTotal {get;set;}
    public integer idlpluspreviousmonthTotal {get;set;}
    public integer caTotal {get;set;}
    public integer ecmtdTotal {get;set;}
    public integer ecpreviousmonthTotal {get;set;}
    public integer ecEligibleYesMTDTotal {get;set;}
    public integer ecEligibleYesPreviosMonthTotal {get;set;}
    public string name {get;set;}
    public integer data {get;set;}
    public integer data1 {get;set;}		// bar chart EC
    public string ecname {get;set;}  // bar chart EC 
    public integer ecdata {get;set;} // bar chart EC 
    public string ecname1 {get;set;}  // bar chart EC 
    public integer ecdata1 {get;set;} // bar chart EC 
    
     
   
	public class EcPerformanceRecordList {
		public String DealerID{get;set;}
		public String submitUserID{get;set;}
		public String bookedDate{get;set;}
		public String ecEligible{get;set;}
		public Integer caBookedCount{get;set;}
		public Integer ecBookedCount{get;set;}
       
        
	}
	
    
	public class CaPerformanceRecordList {
		public String DealerID{get;set;}
		public String dealerName{get;set;}
		public String reportingPeriod{get;set;}
		public String financeSourceIntegrationTypeCode{get;set;}
		public String idlPlus{get;set;}
		public String creditApplicationSourceCode{get;set;}
		public Integer submissionCount{get;set;}
    }
    

}

 
Why does my chart has month names on wedges but the sample example doesn't ? 

In my sandbox I  copied and pasted exact code from the salesforce documentation as shown here https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_charting_overview_simple_example.htm

Created a Apex Controller, Created a Wrapper Class, Created a VFP.
 
The output as shown in this example doesn't have month names on the wedges. However the output I get has month names on the wedges. This example doesn't uses rendererFn property. I am wondering why i see month names and the example shown does'nt?

This is my output 
User-added imageHowever I was expecting to see this 

User-added image

Here the Code exactly as copied from the documentation 
 
<apex:page controller="PieChartController" title="Pie Chart">
    <apex:chart height="350" width="450" data="{!pieData}">
        <apex:pieSeries dataField="data" labelField="name"/>
        <apex:legend position="right"/>
    </apex:chart>
</apex:page>



public class PieChartController {
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        data.add(new PieWedgeData('Jan', 30));
        data.add(new PieWedgeData('Feb', 15));
        data.add(new PieWedgeData('Mar', 10));
        data.add(new PieWedgeData('Apr', 20));
        data.add(new PieWedgeData('May', 20));
        data.add(new PieWedgeData('Jun', 5));
        return data;
    }

    // Wrapper class
    public class PieWedgeData {

        public String name { get; set; }
        public Integer data { get; set; }

        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
}

 
I am trying to get the total count of all records in the list, and display it. Value not displaying . 
 
<apex:page controller="CASReportController">
<apex:form >
    <apex:pageBlock title="JSON Deserialized Response">
    <apex:pageBlockButtons >
        <apex:commandButton value="submit" action="{!deserialize}" reRender="DealerBlock"/>
    </apex:pageBlockButtons>
			
    <apex:pageBlockSection id="DealerBlock" columns="1" title="RollUp Summary >

    <apex:repeat value="{!wrapper}" var="cap1">
                    
    <apex:pageBlockTable value="{!cap1.caPerformanceRecordList}" var="cap" width="100%">

    <apex:column headerValue="Reporting Period" value="{!cap.reportingPeriod}"/>
                            
    <apex:column headerValue="FS Integration Type Code" value="{!cap.financeSourceIntegrationTypeCode}"/>
                            
    <apex:column headerValue="IDL Plus" value="{!cap.idlPlus}"/>
                            
    <apex:column headerValue="Credit Application Source Code" value="{!cap.creditApplicationSourceCode}"/>
                            
    <apex:column headerValue="Submission Count" value="{!cap.submissionCount}" />
                               

<!-- Generating CASubmissionCount total --> 

<apex:variable var="total" value="{!cap1.appTotal}" />		 							

<!--footer of the SubmissionCount -->
     <apex:facet name="footer">           									
          Total Count: <span class="t1"></span>   			   <!--  expecting Total Count = 7 --    submissionCount of one record is 2 and other record is 7 as seen in json string >							
     </apex:facet> 
                             
 </apex:pageBlockTable>
</apex:repeat>            
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

------------------------------------------------------------
public with sharing class CASReportController {
    
@AuraEnabled
    
public list<JSONWrapperController> wrapper {get;set;}

    public void deserialize() {

        try{
            string jsonresponse = '[{ "caPerformanceRecordList": [ {  "submissionCount": 2 }, {  "submissionCount": 5 } ], "ecPerformanceRecordList": [ {   } ] }]';

           
            wrapper = (list<JSONWrapperController>) JSON.deserialize(jsonresponse, list<JSONWrapperController>.class);

            
        } catch (Exception e){
            system.debug('Error---->' +  e.getLineNumber() + e.getMessage());

        }
    }


---------------------------------------------

public class JSONWrapperController {

	public List < CaPerformanceRecordList > caPerformanceRecordList{get;set;}


	public class CaPerformanceRecordList {
	  public String motorDealerID{get;set;}
	  public String dealerName{get;set;}
	  public String reportingPeriod{get;set;}
      public String   financeSourceIntegrationTypeCode{get;set;}
	  public String idlPlus{get;set;}
	  public String creditApplicationSourceCode{get;set;}
	}
	
	@AuraEnabled
         public integer getTotalAppCount() {
              // loop through each element in the     caPerformanceRecordList, till the end of the list.
             // get grand total of submissionCount 
             // return grand total  
        
             integer appTotal = 0;
             for(CaPerformanceRecordList cp : caPerformanceRecordList) {
                 appTotal += cp.submissionCount;
              }
              return appTotal;
         }

}

 
Save error: Unknown property 'VisualforceArrayList.caPerformanceRecordList'	
 
I am trying to create a VFP to display a table  with values from a JSONWrapperController Class. 

<apex:page controller="CASReportController">
    <apex:form >
        <apex:pageBlock title="JSON Deserialized Response"> 
            <apex:pageBlockButtons >
                <apex:commandButton value="submit" action="{!deserialize}" reRender="dealerBlock"/>
            </apex:pageBlockButtons>
           
           
           	<apex:pageBlockSection id="DealerBlock" columns="1">
                 <apex:repeat value="{!wrapper.caPerformanceRecordList}" var="cap">
                    
                  <apex:pageBlockSection columns="2">
                   <apex:facet name="header">Dealer Name {!cap.dealerName}</apex:facet>
                         <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Dealer Id" for="dlrid" />
                            <apex:outputText value="{!cap.motorDealerID}" id="dlrid" />
                         </apex:pageBlockSectionItem>
                         <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Reporting Date " for="rptdt" />
                            <apex:outputText value="{!cap.statementDate}" id="rptdt" />
                         </apex:pageBlockSectionItem>
                        </apex:pageBlockSection>
           
               
        		 </apex:repeat>
			</apex:pageBlockSection>                                                                                         
        </apex:pageBlock> 
    </apex:form>
</apex:page>


==================================

Related components for this visualforce page

This is a snapshot of the actual JSON Response from Endpoint as obtained from Postman: 

{
    "caPerformanceRecordList": [
        
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-05-18",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "STEONE",
            "submissionCount": 2
        },
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-06-27",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "STEONE",
            "submissionCount": 5
        }
    ],
    "ecPerformanceRecordList": [
        {
            "motorDealerID": "XL1HX",
            "submitUserID": "BCUSER1",
            "bookedDate": "2019-05-22 00:00:00.0",
            "ecEligible": "Y",
            "caBookedCount": 1,
            "ecBookedCount": 0
        },
        {
            "motorDealerID": "XL1HX",
            "submitUserID": "BCUSER1",
            "bookedDate": "2019-06-05 00:00:00.0",
            "ecEligible": "Y",
            "caBookedCount": 1,
            "ecBookedCount": 0
        }
    ]
}



=========================================================

public with sharing class CASReportController {
@AuraEnabled
		public list<JSONWrapperController> wrapper {get;set;}
		
		public void deserialize() {
		
			try{
				string jsonresponse = '[{ "caPerformanceRecordList": [ { "motorDealerID": "XL1HX", "dealerName": "Subaru Auto Dealer", "reportingPeriod": "2019-05-18", "financeSourceIntegrationTypeCode": "FIFS", "idlPlus": "Y", "creditApplicationSourceCode": "STEONE", "submissionCount": 2 }, { "motorDealerID": "XL1HX", "dealerName": "Subaru Auto Dealer", "reportingPeriod": "2019-06-27", "financeSourceIntegrationTypeCode": "FIFS", "idlPlus": "Y", "creditApplicationSourceCode": "STEONE", "submissionCount": 5 } ], "ecPerformanceRecordList": [ { "motorDealerID": "XL1HX", "submitUserID": "BCUSER1", "bookedDate": "2019-05-22 00:00:00.0", "ecEligible": "Y", "caBookedCount": 1, "ecBookedCount": 0 }, { "motorDealerID": "XL1HX", "submitUserID": "BCUSER1", "bookedDate": "2019-06-05 00:00:00.0", "ecEligible": "Y", "caBookedCount": 1, "ecBookedCount": 0 } ] }]';
			  
			 	system.debug('json string is ' +jsonresponse);
			 	wrapper = (list<JSONWrapperController>) JSON.deserialize(jsonresponse, list<JSONWrapperController>.class);
			 
		     	system.debug('This is the wrapper class: ' +wrapper);
			 } catch (Exception e){
				system.debug('Error---->' +  e.getLineNumber() + e.getMessage());
				
			}
       }
}

========================================

public class JSONWrapperController {

     public List<CaPerformanceRecordList> caPerformanceRecordList{get;set;}
     public List<EcPerformanceRecordList> ecPerformanceRecordList{get;set;}	
     
     public class EcPerformanceRecordList {
		public String motorDealerID{get;set;}
		public String submitUserID{get;set;}
		public String bookedDate{get;set;}
		public String ecEligible{get;set;}
		public Integer caBookedCount{get;set;}
		public Integer ecBookedCount{get;set;}
	}

	

	public class CaPerformanceRecordList {
		public String motorDealerID{get;set;}
		public String dealerName{get;set;}
		public String reportingPeriod{get;set;}
		public String financeSourceIntegrationTypeCode{get;set;}
		public String idlPlus{get;set;}
		public String creditApplicationSourceCode;
		{get;set;}public Integer submissionCount;
	}

	
	
}
As seen in debug logs , why is the string json on deserializing returning null ? 
 
{
    "caPerformanceRecordList": [
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-05-01",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "ECKNWNSPT",
            "submissionCount": 2
        },
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-05-02",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "RTEONE",
            "submissionCount": 15
        }
    ]
}


public with sharing class CASReportController {

		public list<JSONWrapperController> wrapper {get;set;}

		public void deserialize() {
		
		string jsonresponse = '{"caPerformanceRecordList":[{"motorDealerID":"XL1HX","dealerName":"Subaru Auto Dealer","reportingPeriod":"2019-05-01","financeSourceIntegrationTypeCode":"FIFS","idlPlus":"Y","creditApplicationSourceCode":"ECKNWNSPT","submissionCount":2 },{"motorDealerID":"XL1HX", "dealerName":"Subaru Auto Dealer", "reportingPeriod":"2019-05-02","financeSourceIntegrationTypeCode":"FIFS","idlPlus":"Y","creditApplicationSourceCode":"RTEONE","submissionCount": 15 },{"motorDealerID": "XL1HX", "dealerName":"Subaru Auto Dealer","reportingPeriod":"2019-05-02","financeSourceIntegrationTypeCode":"FIFS","idlPlus":"Y","creditApplicationSourceCode":"RTEONE","submissionCount":14}]}';
		  
		 system.debug('json string is ' +jsonresponse);
		 wrapper = (list<JSONWrapperController>) JSON.deserialize(jsonresponse, lis<JSONWrapperController>.class);
        
        system.debug('This is the wrapper class: ' +wrapper);
	}
}



public class JSONWrapperController {
	
	    public class CaPerformanceRecordList {   
	    	
		public string dealerName {get; set;}
	        public String motorDealerId {get;set;}
	        public DateTime mtd {get; set;}
	        public Integer submissionCount{get;set;}
		public String idlPlus{get;set;}
		public String creditApplicationSourceCode{get;set;}
		    
    	}
	
	 public List<CaPerformanceRecordList> caperfreclist {get;set;} 
   
}


DEBUG|This is the wrapper class: JSONWrapperController:[caperfreclist=null]

 
 json response 
{
    "caPerformanceRecordList": [
       
        {
            "sourceOneDealerID": "XL1HX",
            "dealerName": "Superior Auto Dealer",
            "reportingPeriod": "2019-06-25",
            "financeSourceIntegrationTypeCode": "FIFS",
            "independentdlrPlus": "Y",
            "caApplicationSourceCode": "ECKNWNSPT",
            "submissionCount": 1
        },
        
        {
            "sourceOneDealerID": "XL1HX",
            "dealerName": "Superior Auto Dealer",
            "reportingPeriod": "2019-06-25",
            "financeSourceIntegrationTypeCode": "PIFS",
            "independentdlrPlus": "Y",
            "caApplicationSourceCode": "RTEONE",
            "submissionCount": 1
        },
        {
            "sourceOneDealerID": "XL1HX",
            "dealerName": "Superior Auto Dealer",
            "reportingPeriod": "2019-06-26",
            "financeSourceIntegrationTypeCode": "FIFS",
            "independentdlrPlus": "Y",
            "caApplicationSourceCode": "RTEONE",
            "submissionCount": 15
        }
    ],
    "ecPerformanceRecordList": [
        {
            "sourceOneDealerID": "XL1HX",
            "submitUserID": "ECUSER1",
            "bookedDate": "2019-05-22 00:00:00.0",
            "ecEligible": "Y",
            "caBookedCount": 1,
            "ecBookedCount": 0
        },
        {
            "sourceOneDealerID": "XL1HX",
            "submitUserID": "ECUSER1",
            "bookedDate": "2019-06-05 00:00:00.0",
            "ecEligible": "Y",
            "caBookedCount": 1,
            "ecBookedCount": 0
        }
    ]
}

Using Json2Apex I got this class, 
 
public class JSON2ApexWrapper {

	public class EcPerformanceRecordList {
		public String sourceOneDealerID;
		public String submitUserID;
		public String bookedDate;
		public String ecEligible;
		public Integer caBookedCount;
		public Integer ecBookedCount;
	}

	public class CaPerformanceRecordList {
		public String sourceOneDealerID;
		public String dealerName;
		public String reportingPeriod;
		public String financeSourceIntegrationTypeCode;
		public String independentdlrPlus;
		public String caApplicationSourceCode;
		public Integer submissionCount;
	}

	public List<CaPerformanceRecordList> caPerformanceRecordList;
	public List<EcPerformanceRecordList> ecPerformanceRecordList;

	
	public static JSON2ApexWrapper parse(String json) {
               return (JSON2ApexWrapper) System.JSON.deserialize(json,JSON2ApexWrapper.class);
	}
}
 I want to create a Visualforce page to display a table adds the submissionCount for each day in the list and dislays the total 

e.g   caPerformanceRecordList   MonthtoDate(SubmittedCount) = 17 
       ecPerformanceRecordList:
       MonthtoDate(Total: caBookedCount) =  2
       MonthtoDate(Total: ecBookedCount) = 0

What do i need to change in the wrapper class to be able to calculate these sums and then reference in visualforce page ? 

Thanks you . 
Can some one shed light on the best way to achieve this ?
I want to get the value of a text field from the ParentAccount in an Account Heirarchy on Contact record.   

Contact > Account > ParentAccount > 'text field' 

I am thinking of creating a formula field on Contact  with Psedocode ..

on Contact record if Account field is not null > check if the Account related to the contact, has a parent Account. if yes, populate the parent accounts customtextfield value on Contact
I am trying to optimize my working code. When i tried to convert a set into a Map, I am getting an error -  
Line: 10, Column: 22
Method does not exist or incorrect signature: void add(Id, String) from the type Map<Id,String>

 
Map<ID, String>  mapAccountBillingAddress = new Map<ID, String>();
for (AggregateResult aggregate : [Select count(Id),BillingStreet str,BillingCity ct, BillingState stt, BillingPostalCode pc 
From Account                                                                Group By BillingStreet,BillingCity,BillingState,BillingPostalCode
HAVING (count(BillingStreet) > 1  AND count(BillingPostalCode) > 1 )
] )
{
mapAccountBillingAddress .add(aggregate.id, ((String)aggregate.get('str')+(String)aggregate.get('ct')+(String)aggregate.get('stt')+(String)aggregate.get('pc')));
	
   
}



 
How Can i get a list of Accounts that has the same BillingAddress? 

I tried this and got the error 'Line: 2, Column: 34
HAVING count(BillingAddress)>1 ^ ERROR at Row:5:Column:49 field BillingAddress does not support aggregate operator COUNT'


Set <String>SameBillingAddress = new Set<String>();
for (AggregateResult aggregate : [Select count(Id),BillingAddress
From Account 
Where BillingStreet!= null AND BillingState!=null AND BillingCity!= null AND BillingPostalCode!=Null
Group By BillingAddress
HAVING count(BillingAddress) > 1 
] )
{
    SameBillingAddress.add((String)aggregate.get('BillingAddress'));
}
for (Account acc : [
    SELECT Name, BillingAddress
    FROM Account
    WHERE BillingAddress IN :SameBillingAddress
]){
    system.debug(+ acc.BillingAddress);
How can i trigger the autoproc process so that all the Accounts that are identified as Duplicates are added to the DuplicateRecordSet. ? 

I had an Active Duplicate Rule on Account  'Scenario1 ', based off a Matching rule 'MR1' .  I modified the matching rule, and see that duplicates are correctly being identified and shown as potential duplicates. However, Ever since modifying the matching rule, no DuplicateRecordSets are being created. The only time a new DuplicateRecordSet  is created is when a new duplicate Account is inserted.

Note: So far i have tried this - 

Deleted ole DuplicateRule and recreated a new rule based on the modified matching rule. 
Deleted the existing DuplicateRecordSets that were created as part of the old DuplicateRule. 


 
What would be a best solution for this use case: 

If two Contacts have same FirstName, LastName and Email, and one of the Contact Record Custom_CheckBox__c = true, make it true for other record too. 

My appraoch : 
I was thinking, creating a Custom_Formula_Field__c returning text that is a concatenated string 'FirstNamelastNameEmail' 

Then in Developer Console, querying all Contact records that has  same value in Custom_Formula_Field__c

If one has Checkbox_-c = true, make the other record's Checkbox__c = true


Any suggestions?
Can someone please assist, how do i get around this exception of 'Too many query Rows 5001'

 
list<Id> accId = new list<Id>();

list<Contact> conDSA = [Select Id, Name, DSA__c, AccountID from Contact 
                        Where DSA__c = true AND AccountID!=null ];

system.debug('Number of Contacts that are DSA ' +conDSA.size());
for (Contact c: conDSA){
system.debug('>>> ' +c.Name + c.AccountId);
    accId.add(c.AccountId);

}

list<AccountContactRelation> acr = [SELECT Id, isDSA__c,AccountId, ContactId 
                                    FROM AccountContactRelation 
                                    Where AccountId IN :accId ];

system.debug('Number of records in ACR are: ' +acr.size());

for (AccountContactRelation a: acr){
    	a.isDSA__c = true;
}
update acr;

 
I am trying to iterate over a list in the map, get distinct phone numbers from Accounts in the list and assign the phone number/s in a long text area on new line or comma separated. My attempt so far. .. 
I would be grateful for any suggestions? 
 
//1. Fetch all Accounts associated with each CompanyID__c
//2.  if the List of Accounts for every Key has more than one record then
//3.  fetch the distict phone numbers on all of those accounts and // struggling
//4. store them in a Long Text Area field on new line   // struggling


List<Account> accs = [SELECT Id, Name, CompanyID__c, Phone FROM Account where CompanyID__c!=null];
Map<String, List<Account>> mapR1Accs = new Map<String, List<Account>>();
for (Account a : accs) {
    if (mapR1Accs.containsKey(a.CompanyID__c)){
        mapR1Accs.get(a.CompanyID__c).add(a);
    } else{
        List <Account> lstaccts = new List <Account> ();
    	lstaccts.add(a);
        mapR1Accs.put(a.CompanyID__c,lstaccts);
    }
}

system.debug('This is the map: ' +mapR1Accs);

//For Each of the Key 
 for(String accR1ID : mapR1Accs.keySet()){
    List<Account> accounts = mapR1Accs.get(accR1ID);
    System.debug('There are ' + accounts.size() + ' accounts for companyid ' + accR1ID);
    if (accounts.size()>1) 
		for (Account myaccount : accounts) {
			
			System.debug('The phone number for ' + myaccount.id + ' is ' +myaccount.Phone);
			// How do I get the phone numbers from each of the account in the list ? and 
			// how to I assign it to Backup_PhoneNumber__c long text area field, each phone number on a new line?
			// How do I update these accounts ? 
			// myaccount.Backup_PhoneNumber__c = myaccount.Phone; 
		}
	}
}


This is my debug log so far...


16:23:53:046 USER_DEBUG [13]|DEBUG|This is the map: {IGOAL=(Account:{Id=001M00000170ooaIAA, Name=Cruise - R1 INTERNAL, CompanyID__c=IGOAL, Phone=123-456-7890, RecordTypeId=012E0000000RTEdIAO}, 
															Account:{Id=001M00000170oozIAA, Name=Cruise WEST, CompanyID__c=IGOAL, Phone=222-333-4444, RecordTypeId=012E0000000RTEdIAO}), 
													 ZY9JW=(Account:{Id=001M00000170opsIAA, Name=Ferrari, CompanyID__c=ZY9JW, Phone=333-444-5555, RecordTypeId=012E0000000RTEdIAO},
															Account:{Id=001M00000170optIAA, Name=Malibu, CompanyID__c=ZY9JW, Phone=333-444-5555, RecordTypeId=012E0000000RTEdIAO})}


16:23:53:046 USER_DEBUG [18]|DEBUG|There are 2 accounts for companyid IGOAL
16:23:53:047 USER_DEBUG [22]|DEBUG|The phone number for 001M00000170ooaIAA is 123-456-7890
16:23:53:047 USER_DEBUG [22]|DEBUG|The phone number for 001M00000170oozIAA is 222-333-4444

16:23:53:047 USER_DEBUG [18]|DEBUG|There are 2 accounts for companyid ZY9JW
16:23:53:047 USER_DEBUG [22]|DEBUG|The phone number for 001M00000170opsIAA is 333-444-5555
16:23:53:047 USER_DEBUG [22]|DEBUG|The phone number for 001M00000170optIAA is 333-444-5555

 

global class DuplicateContactMergeBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext bc){
       // collect the batches of records or objects to be passed to execute. 
       // DuplicateRecordSet is a list of Contacts (Duplicate RecordItems) idenified as Duplicates by the Duplicate Rule
    	
		string conduplicateruleid;
		list<DuplicateRulesId__c> cs = [select id, ContactDuplicateRuleId__c from DuplicateRulesId__c limit 1];
		if(cs!=null && cs.size() > 0 ){
			for(DuplicateRulesId__c custsetting: cs){
				
			   conduplicateruleid = custsetting.ContactDuplicateRuleId__c;
				system.debug('++++++++++++++++++    ' +conduplicateruleid);
			 }
		}

		// Fetch Id and Name of the Duplicate Record Set 

		return Database.getQueryLocator([
                SELECT id, name 
                FROM DuplicateRecordSet
                Where DuplicateRuleId = :conduplicateruleid 
            ]);  
		
    }
	
	global void execute(Database.BatchableContext BC, List<DuplicateRecordSet> scope) {
              
       //call MergeContacts method to process each batch of records
        MergeContacts(scope); 
        
    }

	public static void  MergeContacts(List<DuplicateRecordSet> dupset){
	
		//iterate through each DuplicateRecordSet, and create a map of duplicaterecordset<Id, DuplicateRecordSet> 
		Map<Id, DuplicateRecordSet> mapDuplicateRecordSet =  new Map<Id,DuplicateRecordSet>();

		if(dupset!=null && dupset.size()>0){
			for(DuplicateRecordSet drs : dupset){
				mapDuplicateRecordSet.put(drs.Id, drs);
			}
		}
		system.debug('map of duplicate record set' +mapDuplicateRecordSet);
		Map<Id, Set<Id>> mapDuplicateRecordItem =  new Map<Id, Set<Id>>();
		for(DuplicateRecordItem drI : [SELECT Id,RecordId, DuplicateRecordSetId 
									   FROM DuplicateRecordItem 
									   where DuplicateRecordSetId IN :mapDuplicateRecordSet.keyset()]){
					
					System.debug('Duplicate record Items: ' +drI);
					if(drI!=null && !mapDuplicateRecordItem.containskey(drI.DuplicateRecordSetId)){
						mapDuplicateRecordItem.put(drI.DuplicateRecordSetId, new Set<Id>{drI.RecordId}); 
					}
					else{
						mapDuplicateRecordItem.get(drI.DuplicateRecordSetId).add(drI.RecordId); 
					}
		} 

		// create a list of contacts that need to be merged 
		list<id> lstContactId = new list<id>(); 
		Set<Id>  setContactId = new set<id>();
		list<contact> mastercontact = new list<contact>();

		// iterate through all DuplicateRecordSet records that has child records 
		for(DuplicateRecordSet dr : [SELECT Id 
									 FROM DuplicateRecordSet 
									 where Id IN : mapDuplicateRecordItem.keyset()]){
			
			// Collect all disctinct contacts from the duplicaterecorditems
			setContactId =  mapDuplicateRecordItem.get(dr.Id);
			system.debug('The elements in the setofid are :' +setContactId.size());
			system.debug('Each of these elements is :' +setContactId);                             
										 
		}

		for(Contact con : [SELECT Id, lastname,email, ownerid,phone 
							   FROM Contact 
							   WHERE Id In : setContactId 
							   order by CreatedDate DESC LIMIT 1]){		
													   
							   IF(con!=null){
								mastercontact.add(con);
							   }
							   setContactId.remove(con.Id);  
							   lstContactId.addAll(setContactId);  
		}

		system.debug('master contact ' +mastercontact[0]);
		system.debug('new elemensts in the setContactId' +setContactId);
		system.debug('list of dupicated contacts ' +lstContactId);

		if(mastercontact.size()>0 && mastercontact!=null){
			try{
				Database.merge (mastercontact[0],lstContactId, true);
			}	catch (DmlException e) {
				// Process exception
				System.debug('An unexpected error has occurred: ' + e.getMessage()); 
			} 
		}
	
	}

	global void finish(Database.BatchableContext bc){
       // execute any post-processing operations
    }   

}

@isTest 
public class DuplicateContactMergeBatchTest{

    public static testMethod void testContactMerge() {
        
       	// Create a test user        	
       	User oUser = TestDataHelper.createUser('Lender', 'Testra1', 'testra1@emailtest.com', 'Dealer Sales Representative', true);
       	
       	// Create test dealer Accounts
       	Account oAccount1 = TestDataHelper.createAccount('Testonera Account-1', 'Dealer Account', 'RAA-1', oUser.Id, false);
       	Account oAccount2 = TestDataHelper.createAccount('Testtwora Account-2', 'Dealer Account', 'RAA-2', oUser.Id, false);
        
        List<Account> accounts = new List<Account>{oAccount1,oAccount2};
        
        insert accounts;
                
        System.assertEquals( 1, [ SELECT count() FROM Account WHERE id = :oAccount1.id ] );
        System.assertEquals( 1, [ SELECT count() FROM Account WHERE id = :oAccount2.id ] );
        
        //Create a Dealer Contact record
        Contact oContact1 = TestDataHelper.createContact(oAccount1.Id, 'TestConOne', 'TestLastname', 'Dealer Contact', '9995551212', oUser.Id, true);
        
        Contact oContact2 = oContact1.clone(); 
        
        insert oContact2;
        
        System.assertEquals( 1, [ SELECT count() FROM Contact WHERE id = :oContact1.id ] );
        System.assertEquals( 1, [ SELECT count() FROM Contact WHERE id = :oContact2.id ] );
        
        list<Contact> contacts = new list<Contact>();
        contacts.add(oContact1);
        contacts.add(oContact2);
        
        system.debug('The contactlistsize is ' +contacts.size() );
        
        // if no duplicate record sets have been created yet
        // then let's manually insert them so we can test the merge
        Integer dupeCount = [ SELECT count() FROM DuplicateRecordItem WHERE recordId IN :contacts ];
        system.debug('Thiiiiiii ' +dupeCount);
        if ( dupeCount == 0 ) {
            insertDuplicateRecordSet( contacts );
        }
        
        Test.startTest();
            DuplicateContactMergeSched sh1 = new DuplicateContactMergeSched();
            String sch = '0 0 23 * * ?';
            system.schedule('Test DuplicateContactMergeSched', sch, sh1);
        Test.stopTest();
        
    }
    
     private static void insertDuplicateRecordSet( List<Contact> contacts ) {
     
        //Database.DMLOptions insertDML = new Database.DMLOptions(); 
        //insertDML.DuplicateRuleHeader.AllowSave = true; 
        
        DuplicateRule rule = [ SELECT id FROM DuplicateRule 
                                WHERE DeveloperName = 'Standard_Rule_for_Contacts_with_Duplicate_Contacts' LIMIT 1 ];
                                
                                system.debug('RULLLLLLLLLeeee ' +rule.id);
                                
        //Database.SaveResult[] sr = Database.insert(contacts, insertDML);        
        DuplicateRecordSet drs = new DuplicateRecordSet(
            duplicateRuleId = rule.id
        );
        
        insert drs;
        
        system.debug('>>>>>>>>>>>>' +drs);

        List<DuplicateRecordItem> items = new List<DuplicateRecordItem>();
        
        for ( Contact cnt : contacts ) {
            items.add( new DuplicateRecordItem(
                duplicateRecordSetId = drs.id,
                recordId = cnt.id
            ));
        }
        
        insert items;
        
    }
    
}


 
global class DuplicateContactMergeSched implements Schedulable{
   global void execute(SchedulableContext SC) {
    DuplicateContactMergeBatch b = new DuplicateContactMergeBatch(); 
    database.executebatch(b);      
    }
}
Code covergae is only 17%. The entire execute method (highlighted in bold is not covered). 
Any suggestions?
Based on my previous learnings about auto merging duplicate accounts, I set to write code to merge contacts. 
I tested each line in developer console, it works. Of course the code is not robust and has several flaws but i will get there!  

my question is , Can someone review my code and provide constructive feedback. 
Thanks!
// Created DuplicateRule for Contacts in Setup based //on standard matching rule. 
//From the DuplicatedRecordSet, fetching all //DuplicateRecordItems, which are the duplicate //Contacts.

global class DuplicateContactMergeBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext bc){
       // collect the batches of records or objects to be passed to execute. 
       // DuplicateRecordSet is a list of Contacts (Duplicate RecordItems) idenified as Duplicates by the Duplicate Rule
    	
		string conduplicateruleid;
		list<DuplicateRulesId__c> cs = [select id, ContactDuplicateRuleId__c from DuplicateRulesId__c limit 1];
		if(cs!=null && cs.size() > 0 ){
			for(DuplicateRulesId__c custsetting: cs){
				
			   conduplicateruleid = custsetting.ContactDuplicateRuleId__c;
				system.debug('++++++++++++++++++    ' +conduplicateruleid);
			 }
		}

		// Fetch Id and Name of the Duplicate Record Set 

		return Database.getQueryLocator([
                SELECT id, name 
                FROM DuplicateRecordSet
                Where DuplicateRuleId = :conduplicateruleid 
            ]);  
		
    }
	
	global void execute(Database.BatchableContext BC, List<DuplicateRecordSet> scope) {
              
       //call MergeAccounts method to process each batch of records
        MergeContacts(scope); 
        
    }

	public static void  MergeContacts(List<DuplicateRecordSet> dupset){
	
		//iterate through each DuplicateRecordSet, and create a map of duplicaterecordset<Id, DuplicateRecordSet> 
		Map<Id, DuplicateRecordSet> mapDuplicateRecordSet =  new Map<Id,DuplicateRecordSet>();

		if(dupset!=null && dupset.size()>0){
			for(DuplicateRecordSet drs : dupset){
				mapDuplicateRecordSet.put(drs.Id, drs);
			}
		}
		system.debug('map of duplicate record set' +mapDuplicateRecordSet);
		Map<Id, Set<Id>> mapDuplicateRecordItem =  new Map<Id, Set<Id>>();
		for(DuplicateRecordItem drI : [SELECT Id,RecordId, DuplicateRecordSetId 
									   FROM DuplicateRecordItem 
									   where DuplicateRecordSetId IN :mapDuplicateRecordSet.keyset()]){
					
					System.debug('Duplicate record Items: ' +drI);
					if(drI!=null && !mapDuplicateRecordItem.containskey(drI.DuplicateRecordSetId)){
						mapDuplicateRecordItem.put(drI.DuplicateRecordSetId, new Set<Id>{drI.RecordId}); 
					}
					else{
						mapDuplicateRecordItem.get(drI.DuplicateRecordSetId).add(drI.RecordId); 
					}
		} 

		// create a list of contacts that need to be merged 
		list<id> lstContactId = new list<id>(); 
		Set<Id>  setContactId = new set<id>();
		list<contact> mastercontact = new list<contact>();

		// iterate through all DuplicateRecordSet records that has child records 
		for(DuplicateRecordSet dr : [SELECT Id 
									 FROM DuplicateRecordSet 
									 where Id IN : mapDuplicateRecordItem.keyset()]){
			
			// Collect all disctinct contacts from the duplicaterecorditems
			setContactId =  mapDuplicateRecordItem.get(dr.Id);
			system.debug('The elements in the setofid are :' +setContactId.size());
			system.debug('Each of these elements is :' +setContactId);                             
										 
		}

		for(Contact con : [SELECT Id, lastname,email, ownerid,phone 
							   FROM Contact 
							   WHERE Id In : setContactId 
							   order by CreatedDate DESC LIMIT 1]){		
													   
							   IF(con!=null){
								mastercontact.add(con);
							   }
							   setContactId.remove(con.Id);  
							   lstContactId.addAll(setContactId);  
		}

		system.debug('master contact ' +mastercontact[0]);
		system.debug('new elemensts in the setContactId' +setContactId);
		system.debug('list of dupicated contacts ' +lstContactId);

		if(mastercontact.size()>0 && mastercontact!=null){
			try{
				Database.merge (mastercontact[0],lstContactId, true);
			}	catch (DmlException e) {
				// Process exception
				System.debug('An unexpected error has occurred: ' + e.getMessage()); 
			} 
		}
	
	}

	global void finish(Database.BatchableContext bc){
       // execute any post-processing operations
    }   

}

 
The salesforce org i am currently working on, instead of setting up many to many relationship between Account and Contact, they have multiple instances of the same contact, and each instance is related to unique account. 
E.g. In our org we have 200 Accounts for each of the 200 franchicess that do business with us. The person in charge (may be the area manager) for each of these stores is Sam Watkins. So in the org we have created Sam Watkins 200 times and related her to each of the Franchise. 
Sam Watkins  sam@email.com SW12  related to Account Acc001
Sam Watkins  sam@email.com SW12  related to Account Acc002
Where SW12 is the contacts unique identifier

In search if i type SW12, the list shows  all the 200 Accounst this person is related to.  

I have proposed to set up many to many relation between Account and Contacts so that we don't duplicate the same contact several hundered times, and also be able to build meaniful reports.  

My question is I want to fetch all instances of same Contacts that are associated with multiple accounts. 

This is how I can get one email at a time, but how can i get all contacts based on email addresses of all the Contacts who have multiple instances in the org.   
 
//retrieve related accounts for a contact
List<Contact> contactList = [Select id, name, AccountID
                       from contact where Email = 'sam@email.com'];

for(Contact con : contactList) {
    System.debug('Account id : ' + con.AccountID);
}

Thanks!
I have two active duplicate rules on Account in production . 
Now when i am trying to deploy my code for merging duplicate accounts, the deployment fails for  a class that already exists in production. If i disable the duplicate rule, the  test class that I am trying to deploy will fail because it check for active duplicate rules. 

I did some research and found a workaround as follows. 
My question is, do i have to add this workaround in my test class or the main class.  Thank you !

Database.DMLOptions dml = new Database.DMLOptions(); dml.DuplicateRuleHeader.AllowSave = true; Account duplicateAccount = new Account(Name='dupe'); Database.SaveResult sr = Database.insert(duplicateAccount, dml); if (sr.isSuccess()) { System.debug('Duplicate account has been inserted in Salesforce!'); }
Can someone please assist, how do i get around this exception of 'Too many query Rows 5001'

 
list<Id> accId = new list<Id>();

list<Contact> conDSA = [Select Id, Name, DSA__c, AccountID from Contact 
                        Where DSA__c = true AND AccountID!=null ];

system.debug('Number of Contacts that are DSA ' +conDSA.size());
for (Contact c: conDSA){
system.debug('>>> ' +c.Name + c.AccountId);
    accId.add(c.AccountId);

}

list<AccountContactRelation> acr = [SELECT Id, isDSA__c,AccountId, ContactId 
                                    FROM AccountContactRelation 
                                    Where AccountId IN :accId ];

system.debug('Number of records in ACR are: ' +acr.size());

for (AccountContactRelation a: acr){
    	a.isDSA__c = true;
}
update acr;

 
i am trying to display the time from Apex controller to Lightning component. 
is it possible to directly get Datetime.now () in the js controller and display it on the component? 



({	
	ctr : function(cmp, event, helper) {
        var temp = [];
       
        var action = cmp.get("c.getGraph");
        action.setParams({
        	"accountid": cmp.get("v.recordId")
       	});
        action.setCallback(this, function(response){
            if(response.getState() === 'SUCCESS' && response.getReturnValue()){
                temp = response.getReturnValue();
                helper.createGraph(cmp, temp);
            }
        });      
          
       $A.enqueueAction(action);
      
	},
    
    cancelAction: function(component, event, helper) {
   		$A.get("e.force:closeQuickAction").fire();
	}
})



 
Can some one plese assist? 

If you look at my wrapper class, there is an inner class EcPerformanceRecordList .I have declared a list<EcPerformanceRecordList>  for getting and setting values between controller and UI

When i try to create a map so that I have a list of EcPerformaceRecordList per User, I get an error when I declare the map as map<String,<list<EcPerformanceRecordList>>

How can i declare a Map and loop through this map so that I can count how many apps have been submitted per user.
e.g 
    UserID  Total  EC(Yes)     Date
    user1   12      4          06/12/2019
    user1   13      13         06/13/2019
    user2   35      24         06/18/2019
    user3   23      31         07/02/2019    
    user1   17       2          07/10/2019
    user3   12       3          07/10/2019

I am trying something like this 
Map<userid, list<ecRecordList>> mapname = newMap<userid, list<ecRecordList>> 

mapname.put(user1, <{user1 12 4 06/12/2019}, {user1 13 13 06/13/2019},{user1 17 2 07/10/2019} )

mapname.put(user2, <{ user2 35 24 06/18/2019}, {user1 13 13 06/13/2019},{user1 17 2 07/10/2019} ) and so on.

then for each user, i want to loop through the list and calculate the totals. 
 

Here's snippet of my code for reference.  


public with sharing class MyController {

		public list<MyWrapper> wrapper {get;set;}
    	public integer appTotal {get;set;} 
    	public integer mtdappTotal {get;set;} 
    	public integer previousmonthappTotal {get;set;} 
    	public integer idlplusmtdTotal {get;set;}
    	public integer idlpluspreviousmonthTotal {get;set;}
    	public integer caTotal {get;set;}
    	public integer ecmtdTotal {get;set;}
    	public integer ecpreviousmonthTotal {get;set;}
    	public integer ecEligibleYesMTDTotal {get;set;}
    	public integer ecEligibleYesPreviosMonthTotal {get;set;}
    	public set<String> userid {get;set;}
		public Map<String,list<EcPerformanceRecordList>> ecperuserMap {get;set;}
    
    	
    	@AuraEnabled(cacheable=true)
		public void getdeserialize() {
		
			try{
                string jsonresponse = 'SOME STRING'
			   
			 	
                wrapper = (list<MyWrapper>) JSON.deserialize(jsonresponse, list<MyWrapper>.class);
			 	
                
                // call the method that aggregates the MonthToDate app count, and PreviousMonth app count per user 
                getTotalECBookedByUser(wrapper);
               
              
		     	
			} catch (Exception e){
				system.debug('Error---->' +  e.getLineNumber() + e.getMessage());
				
			}
    	}
    
    	
    
    // This method calclates the total EC Booked current month and previous month by each user 
    public integer getTotalECBookedByUser(list<MyWrapper> wrapper) {
        	     
        
		Map<String,list<EcPerformanceRecordList>> ecperuserMap = new Map<String,list<EcPerformanceRecordList>>();  
		for(MyWrapper jw: wrapper){
            
            jw.ecpreviousmonthTotal=0;
			jw.ecmtdTotal = 0;   
        	// create a map of submitUserID and ECSubmittedRecordList 
			Map<String,list<EcPerformanceRecordList>> ecperuserMap = new Map<String,list<EcPerformanceRecordList>>();  
        	 
        	for (MyWrapper.EcPerformanceRecordList ec : jw.ecPerformanceRecordList) {
            	
				if(ecperuserMap.containsKey(ec.submitUserID)){
				
					 ecperuserMap.get(ec.submitUserID).add(ec);

				}else {
				
					ecperuserMap.put(ec.submitUserID,ec);
				}
				          	  
            }
        }
		
		// loop through the map ecperuserMap and count the total apps submitted by each user this month and previous month 
		
		
        
        return ecpreviousmonthTotal;
        return ecmtdTotal;
	
    }
    
  
     
}




------------------------Wrapper Class ------------------


public class MyWrapper {
@AuraEnabled	
    public List<CaPerformanceRecordList> caPerformanceRecordList{get;set;}
    public List<EcPerformanceRecordList> ecPerformanceRecordList{get;set;}
    public Map<String,List<EcPerformanceRecordList>> ecPerUser {get;set;}
    public integer appTotal{get;set;}
    public integer mtdappTotal {get;set;} 
    public integer previousmonthappTotal {get;set;} 
    public integer idlplusmtdTotal {get;set;}
    public integer idlpluspreviousmonthTotal {get;set;}
    public integer caTotal {get;set;}
    public integer ecmtdTotal {get;set;}
    public integer ecpreviousmonthTotal {get;set;}
    public integer ecEligibleYesMTDTotal {get;set;}
    public integer ecEligibleYesPreviosMonthTotal {get;set;}
    public string name {get;set;}
    public integer data {get;set;}
    public integer data1 {get;set;}		// bar chart EC
    public string ecname {get;set;}  // bar chart EC 
    public integer ecdata {get;set;} // bar chart EC 
    public string ecname1 {get;set;}  // bar chart EC 
    public integer ecdata1 {get;set;} // bar chart EC 
    
     
   
	public class EcPerformanceRecordList {
		public String DealerID{get;set;}
		public String submitUserID{get;set;}
		public String bookedDate{get;set;}
		public String ecEligible{get;set;}
		public Integer caBookedCount{get;set;}
		public Integer ecBookedCount{get;set;}
       
        
	}
	
    
	public class CaPerformanceRecordList {
		public String DealerID{get;set;}
		public String dealerName{get;set;}
		public String reportingPeriod{get;set;}
		public String financeSourceIntegrationTypeCode{get;set;}
		public String idlPlus{get;set;}
		public String creditApplicationSourceCode{get;set;}
		public Integer submissionCount{get;set;}
    }
    

}

 
Why does my chart has month names on wedges but the sample example doesn't ? 

In my sandbox I  copied and pasted exact code from the salesforce documentation as shown here https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_charting_overview_simple_example.htm

Created a Apex Controller, Created a Wrapper Class, Created a VFP.
 
The output as shown in this example doesn't have month names on the wedges. However the output I get has month names on the wedges. This example doesn't uses rendererFn property. I am wondering why i see month names and the example shown does'nt?

This is my output 
User-added imageHowever I was expecting to see this 

User-added image

Here the Code exactly as copied from the documentation 
 
<apex:page controller="PieChartController" title="Pie Chart">
    <apex:chart height="350" width="450" data="{!pieData}">
        <apex:pieSeries dataField="data" labelField="name"/>
        <apex:legend position="right"/>
    </apex:chart>
</apex:page>



public class PieChartController {
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        data.add(new PieWedgeData('Jan', 30));
        data.add(new PieWedgeData('Feb', 15));
        data.add(new PieWedgeData('Mar', 10));
        data.add(new PieWedgeData('Apr', 20));
        data.add(new PieWedgeData('May', 20));
        data.add(new PieWedgeData('Jun', 5));
        return data;
    }

    // Wrapper class
    public class PieWedgeData {

        public String name { get; set; }
        public Integer data { get; set; }

        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
}

 
I am trying to get the total count of all records in the list, and display it. Value not displaying . 
 
<apex:page controller="CASReportController">
<apex:form >
    <apex:pageBlock title="JSON Deserialized Response">
    <apex:pageBlockButtons >
        <apex:commandButton value="submit" action="{!deserialize}" reRender="DealerBlock"/>
    </apex:pageBlockButtons>
			
    <apex:pageBlockSection id="DealerBlock" columns="1" title="RollUp Summary >

    <apex:repeat value="{!wrapper}" var="cap1">
                    
    <apex:pageBlockTable value="{!cap1.caPerformanceRecordList}" var="cap" width="100%">

    <apex:column headerValue="Reporting Period" value="{!cap.reportingPeriod}"/>
                            
    <apex:column headerValue="FS Integration Type Code" value="{!cap.financeSourceIntegrationTypeCode}"/>
                            
    <apex:column headerValue="IDL Plus" value="{!cap.idlPlus}"/>
                            
    <apex:column headerValue="Credit Application Source Code" value="{!cap.creditApplicationSourceCode}"/>
                            
    <apex:column headerValue="Submission Count" value="{!cap.submissionCount}" />
                               

<!-- Generating CASubmissionCount total --> 

<apex:variable var="total" value="{!cap1.appTotal}" />		 							

<!--footer of the SubmissionCount -->
     <apex:facet name="footer">           									
          Total Count: <span class="t1"></span>   			   <!--  expecting Total Count = 7 --    submissionCount of one record is 2 and other record is 7 as seen in json string >							
     </apex:facet> 
                             
 </apex:pageBlockTable>
</apex:repeat>            
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

------------------------------------------------------------
public with sharing class CASReportController {
    
@AuraEnabled
    
public list<JSONWrapperController> wrapper {get;set;}

    public void deserialize() {

        try{
            string jsonresponse = '[{ "caPerformanceRecordList": [ {  "submissionCount": 2 }, {  "submissionCount": 5 } ], "ecPerformanceRecordList": [ {   } ] }]';

           
            wrapper = (list<JSONWrapperController>) JSON.deserialize(jsonresponse, list<JSONWrapperController>.class);

            
        } catch (Exception e){
            system.debug('Error---->' +  e.getLineNumber() + e.getMessage());

        }
    }


---------------------------------------------

public class JSONWrapperController {

	public List < CaPerformanceRecordList > caPerformanceRecordList{get;set;}


	public class CaPerformanceRecordList {
	  public String motorDealerID{get;set;}
	  public String dealerName{get;set;}
	  public String reportingPeriod{get;set;}
      public String   financeSourceIntegrationTypeCode{get;set;}
	  public String idlPlus{get;set;}
	  public String creditApplicationSourceCode{get;set;}
	}
	
	@AuraEnabled
         public integer getTotalAppCount() {
              // loop through each element in the     caPerformanceRecordList, till the end of the list.
             // get grand total of submissionCount 
             // return grand total  
        
             integer appTotal = 0;
             for(CaPerformanceRecordList cp : caPerformanceRecordList) {
                 appTotal += cp.submissionCount;
              }
              return appTotal;
         }

}

 
Save error: Unknown property 'VisualforceArrayList.caPerformanceRecordList'	
 
I am trying to create a VFP to display a table  with values from a JSONWrapperController Class. 

<apex:page controller="CASReportController">
    <apex:form >
        <apex:pageBlock title="JSON Deserialized Response"> 
            <apex:pageBlockButtons >
                <apex:commandButton value="submit" action="{!deserialize}" reRender="dealerBlock"/>
            </apex:pageBlockButtons>
           
           
           	<apex:pageBlockSection id="DealerBlock" columns="1">
                 <apex:repeat value="{!wrapper.caPerformanceRecordList}" var="cap">
                    
                  <apex:pageBlockSection columns="2">
                   <apex:facet name="header">Dealer Name {!cap.dealerName}</apex:facet>
                         <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Dealer Id" for="dlrid" />
                            <apex:outputText value="{!cap.motorDealerID}" id="dlrid" />
                         </apex:pageBlockSectionItem>
                         <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Reporting Date " for="rptdt" />
                            <apex:outputText value="{!cap.statementDate}" id="rptdt" />
                         </apex:pageBlockSectionItem>
                        </apex:pageBlockSection>
           
               
        		 </apex:repeat>
			</apex:pageBlockSection>                                                                                         
        </apex:pageBlock> 
    </apex:form>
</apex:page>


==================================

Related components for this visualforce page

This is a snapshot of the actual JSON Response from Endpoint as obtained from Postman: 

{
    "caPerformanceRecordList": [
        
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-05-18",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "STEONE",
            "submissionCount": 2
        },
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-06-27",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "STEONE",
            "submissionCount": 5
        }
    ],
    "ecPerformanceRecordList": [
        {
            "motorDealerID": "XL1HX",
            "submitUserID": "BCUSER1",
            "bookedDate": "2019-05-22 00:00:00.0",
            "ecEligible": "Y",
            "caBookedCount": 1,
            "ecBookedCount": 0
        },
        {
            "motorDealerID": "XL1HX",
            "submitUserID": "BCUSER1",
            "bookedDate": "2019-06-05 00:00:00.0",
            "ecEligible": "Y",
            "caBookedCount": 1,
            "ecBookedCount": 0
        }
    ]
}



=========================================================

public with sharing class CASReportController {
@AuraEnabled
		public list<JSONWrapperController> wrapper {get;set;}
		
		public void deserialize() {
		
			try{
				string jsonresponse = '[{ "caPerformanceRecordList": [ { "motorDealerID": "XL1HX", "dealerName": "Subaru Auto Dealer", "reportingPeriod": "2019-05-18", "financeSourceIntegrationTypeCode": "FIFS", "idlPlus": "Y", "creditApplicationSourceCode": "STEONE", "submissionCount": 2 }, { "motorDealerID": "XL1HX", "dealerName": "Subaru Auto Dealer", "reportingPeriod": "2019-06-27", "financeSourceIntegrationTypeCode": "FIFS", "idlPlus": "Y", "creditApplicationSourceCode": "STEONE", "submissionCount": 5 } ], "ecPerformanceRecordList": [ { "motorDealerID": "XL1HX", "submitUserID": "BCUSER1", "bookedDate": "2019-05-22 00:00:00.0", "ecEligible": "Y", "caBookedCount": 1, "ecBookedCount": 0 }, { "motorDealerID": "XL1HX", "submitUserID": "BCUSER1", "bookedDate": "2019-06-05 00:00:00.0", "ecEligible": "Y", "caBookedCount": 1, "ecBookedCount": 0 } ] }]';
			  
			 	system.debug('json string is ' +jsonresponse);
			 	wrapper = (list<JSONWrapperController>) JSON.deserialize(jsonresponse, list<JSONWrapperController>.class);
			 
		     	system.debug('This is the wrapper class: ' +wrapper);
			 } catch (Exception e){
				system.debug('Error---->' +  e.getLineNumber() + e.getMessage());
				
			}
       }
}

========================================

public class JSONWrapperController {

     public List<CaPerformanceRecordList> caPerformanceRecordList{get;set;}
     public List<EcPerformanceRecordList> ecPerformanceRecordList{get;set;}	
     
     public class EcPerformanceRecordList {
		public String motorDealerID{get;set;}
		public String submitUserID{get;set;}
		public String bookedDate{get;set;}
		public String ecEligible{get;set;}
		public Integer caBookedCount{get;set;}
		public Integer ecBookedCount{get;set;}
	}

	

	public class CaPerformanceRecordList {
		public String motorDealerID{get;set;}
		public String dealerName{get;set;}
		public String reportingPeriod{get;set;}
		public String financeSourceIntegrationTypeCode{get;set;}
		public String idlPlus{get;set;}
		public String creditApplicationSourceCode;
		{get;set;}public Integer submissionCount;
	}

	
	
}
As seen in debug logs , why is the string json on deserializing returning null ? 
 
{
    "caPerformanceRecordList": [
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-05-01",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "ECKNWNSPT",
            "submissionCount": 2
        },
        {
            "motorDealerID": "XL1HX",
            "dealerName": "Subaru Auto Dealer",
            "reportingPeriod": "2019-05-02",
            "financeSourceIntegrationTypeCode": "FIFS",
            "idlPlus": "Y",
            "creditApplicationSourceCode": "RTEONE",
            "submissionCount": 15
        }
    ]
}


public with sharing class CASReportController {

		public list<JSONWrapperController> wrapper {get;set;}

		public void deserialize() {
		
		string jsonresponse = '{"caPerformanceRecordList":[{"motorDealerID":"XL1HX","dealerName":"Subaru Auto Dealer","reportingPeriod":"2019-05-01","financeSourceIntegrationTypeCode":"FIFS","idlPlus":"Y","creditApplicationSourceCode":"ECKNWNSPT","submissionCount":2 },{"motorDealerID":"XL1HX", "dealerName":"Subaru Auto Dealer", "reportingPeriod":"2019-05-02","financeSourceIntegrationTypeCode":"FIFS","idlPlus":"Y","creditApplicationSourceCode":"RTEONE","submissionCount": 15 },{"motorDealerID": "XL1HX", "dealerName":"Subaru Auto Dealer","reportingPeriod":"2019-05-02","financeSourceIntegrationTypeCode":"FIFS","idlPlus":"Y","creditApplicationSourceCode":"RTEONE","submissionCount":14}]}';
		  
		 system.debug('json string is ' +jsonresponse);
		 wrapper = (list<JSONWrapperController>) JSON.deserialize(jsonresponse, lis<JSONWrapperController>.class);
        
        system.debug('This is the wrapper class: ' +wrapper);
	}
}



public class JSONWrapperController {
	
	    public class CaPerformanceRecordList {   
	    	
		public string dealerName {get; set;}
	        public String motorDealerId {get;set;}
	        public DateTime mtd {get; set;}
	        public Integer submissionCount{get;set;}
		public String idlPlus{get;set;}
		public String creditApplicationSourceCode{get;set;}
		    
    	}
	
	 public List<CaPerformanceRecordList> caperfreclist {get;set;} 
   
}


DEBUG|This is the wrapper class: JSONWrapperController:[caperfreclist=null]

 
Hi all,

I'm new to Apex but have been tasked with making one small change to an old Apex Class.
 
public with sharing class WorkDetailUtilities
{
    public static List<SVMXC__Service_Order_Line__c> AddWorkDetails(SVMXC__Service_Order__c WorkOrder, WorkDetailUtilities.FSGCart FSGCart, 
                                Id WorkDetailRTId, List<FSGItemWrapper> MissingCartItems, Id WorkDetailId) 
    {
        system.debug(LoggingLevel.INFO, 'WorkOrder: ' + WorkOrder + ', FSGCart: ' + FSGCart + ', WorkDetailRTId: ' + WorkDetailRTId + ', WorkDetailId: ' + WorkDetailId);
        List<SVMXC__Service_Order_Line__c> WorkOrderLines = new List<SVMXC__Service_Order_Line__c>();
        Map<String, WorkDetailUtilities.FSGItemWrapper> mapPartQuantity = new Map<String, WorkDetailUtilities.FSGItemWrapper>();
        String STDWorkshopHoursProductCode = Label.STD_Workshop_Hours_Product_Code;
        SVMXC__Service_Order_Line__c PSWorkDetail;
        
        try 
        {
            for(WorkDetailUtilities.FSGItemWrapper FSGCartItem :FSGCart.CartItems) 
            {
                system.debug(LoggingLevel.INFO, 'FSGCartItem: ' + FSGCartItem);
                if (FSGCartItem.Part != STDWorkshopHoursProductCode && !FSGCartItem.Part.contains('-'))
                {
                    mapPartQuantity.put('00-' + FSGCartItem.Part, FSGCartItem);
                }
                else
                {
                    mapPartQuantity.put(FSGCartItem.Part, FSGCartItem);
                }    
            }
            system.debug(LoggingLevel.INFO, 'mapPartQuantity: ' + mapPartQuantity);
            
            if (String.isNotBlank(WorkDetailId))
            {
                PSWorkDetail = [SELECT Id, SVMXC__Serial_Number__c, SVMX_Line_Branch_Code__c FROM SVMXC__Service_Order_Line__c WHERE Id =:WorkDetailId];
            }
            system.debug(LoggingLevel.INFO, 'PSWorkDetail: ' + PSWorkDetail);
            
            List<Product2> lstProducts = new List<Product2>([SELECT Id, ProductCode, Name,SVMX_Extra_Description__c,SVMXC__Product_Cost__c FROM Product2 WHERE ProductCode IN :mapPartQuantity.keySet() 
                        AND SMVX_Sales_Company__c =:WorkOrder.SVMXC__Company__r.SVMX_Sales_Company__c AND IsActive = true]);
            system.debug(LoggingLevel.INFO, 'lstProducts: ' + lstProducts);
The change should be (where marked in bold) that instead of '00-' being added it should take the value from the field prefix__c on the Product object. If I add that in instead like: 

mapPartQuantity.put(prefix__c + FSGCartItem.Part, FSGCartItem);

I get the error Error: Compile Error: Variable does not exist: prefix__c at line 19 column 41. 

I guess I need to add that field in somewhere before, but where?

Any help will be much appreciated.
  • June 17, 2019
  • Like
  • 0
I am trying to optimize my working code. When i tried to convert a set into a Map, I am getting an error -  
Line: 10, Column: 22
Method does not exist or incorrect signature: void add(Id, String) from the type Map<Id,String>

 
Map<ID, String>  mapAccountBillingAddress = new Map<ID, String>();
for (AggregateResult aggregate : [Select count(Id),BillingStreet str,BillingCity ct, BillingState stt, BillingPostalCode pc 
From Account                                                                Group By BillingStreet,BillingCity,BillingState,BillingPostalCode
HAVING (count(BillingStreet) > 1  AND count(BillingPostalCode) > 1 )
] )
{
mapAccountBillingAddress .add(aggregate.id, ((String)aggregate.get('str')+(String)aggregate.get('ct')+(String)aggregate.get('stt')+(String)aggregate.get('pc')));
	
   
}



 
How Can i get a list of Accounts that has the same BillingAddress? 

I tried this and got the error 'Line: 2, Column: 34
HAVING count(BillingAddress)>1 ^ ERROR at Row:5:Column:49 field BillingAddress does not support aggregate operator COUNT'


Set <String>SameBillingAddress = new Set<String>();
for (AggregateResult aggregate : [Select count(Id),BillingAddress
From Account 
Where BillingStreet!= null AND BillingState!=null AND BillingCity!= null AND BillingPostalCode!=Null
Group By BillingAddress
HAVING count(BillingAddress) > 1 
] )
{
    SameBillingAddress.add((String)aggregate.get('BillingAddress'));
}
for (Account acc : [
    SELECT Name, BillingAddress
    FROM Account
    WHERE BillingAddress IN :SameBillingAddress
]){
    system.debug(+ acc.BillingAddress);
What would be a best solution for this use case: 

If two Contacts have same FirstName, LastName and Email, and one of the Contact Record Custom_CheckBox__c = true, make it true for other record too. 

My appraoch : 
I was thinking, creating a Custom_Formula_Field__c returning text that is a concatenated string 'FirstNamelastNameEmail' 

Then in Developer Console, querying all Contact records that has  same value in Custom_Formula_Field__c

If one has Checkbox_-c = true, make the other record's Checkbox__c = true


Any suggestions?