• Ravi Dutt Sharma
  • PRO
  • 2277 Points
  • Member since 2014
  • Salesforce


  • Chatter
    Feed
  • 71
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 18
    Questions
  • 524
    Replies
Hi,
I am need to to salesforce, I am writing a visualforce page to display check boxes and list of accounts with a process button. Upon slecting the accounts and the check boxes the process button should contain a method which displays the list of contacts related to selected accounts.
I am unable to retrieve the list of contact names using the selected accounts.I am getting an error when i use a soql query to retrieve the contacts using the account id.

Below is my apex code for above requirment.
Please let me know if my question is not clear.


public class accountcontactwrap {
 public list<accountwrap> warpacc{get;set;}
 public list<account> selectedAccounts{get;set;}
 public list<contact> cont{get;set;}
// public list<contactwrap> wrapcon{get;set;}
  public accountcontactwrap(){
   warpacc=new list<accountwrap>();
   for(account ab:[select id,name,phone from account limit 10]){
    warpacc.add(new accountwrap(ab));
   }
  }
  
public void showcontacts(){
cont=new list<contact>();
 for(accountwrap warpobj:warpacc)
 {
  if(warpobj.isSelected==true){
  cont=[select lastname from contact where account.id=warpobj.acc.id];
   
  }
 }
}

 public class accountwrap{
 public account acc{get;set;}
 public boolean isSelected{get;set;}
  public accountwrap(account a){
   acc=a;
   isSelected=false; 
  }
I have written a test class for which it is showing 45% coverage, when i clicked on the code coverage to see what part of my code is not tested, the option is none and i cant see all tests option also i cannot see the blue and red coloured highlights in my test class? how can i see the coloured highlights and how can i get the all tests option?
THANKS!
Hi Gurus,
I have a trigger which inturn calls a apex method to make a API call to the third party.  After the third party returns the response, I should he updating the values on the record which called the API.

I am able to capture the response but while updating the record I am getting the error.  I am sure, the way I am calling the update method is causing the issue.  

Here is the trigger code:
-------------------------------------------

trigger updateSEToTR on Service_Entity__c (after insert, after update) { 
    //instead of calling the method directly, first iterate over all records and collects Ids of all records to be processed.
    //synchSEDeptSitesToTR.syncSEToTR();
       List<Id> lstSEToUpdate=new List<Id>(); 
        system.debug('---Inside---');
        if((Trigger.isInsert && Trigger.isAfter) || (Trigger.isUpdate && Trigger.isAfter))
        //if((Trigger.isInsert && Trigger.isAfter))
        {
            for(Service_Entity__c se : (List<Service_Entity__c>)trigger.new)
            {   
                If (se.Sync_Status__c<>'Error' && se.Send_To_TR__c==True)
                {
                    lstSEToUpdate.add(se.Id);
                }
            }
        system.debug('---lstSEToUpdate.size()---'+lstSEToUpdate.size());    
        //if there are records to update, call future method for callout, future method can only take list of Ids and can't take objects. Also Trigger.New and Trigger.IsInsert etc will not work in future method.
         If (lstSEToUpdate.size()> 0){
            synchSEDeptSitesToTR.syncSEToTR(lstSEToUpdate);
            synchSEDeptSitesToTR.LockSERecord(lstSEToUpdate);
         }

    }system.debug('-At the End--lstSEToUpdate.size()---'+lstSEToUpdate.size());        
}
-------------------------------------------
Here is the Apex code:
--------------------------------------------
public class synchSEDeptSitesToTR {
   @Future(callout=true) //needed to change the annotation
    public static void syncSEToTR(List<String> serviceEntityIds) {
        String trCustomerCode,trCustomerId,syncStatus,syncErrorMessage;
        List<Id> lstServiceEntitiesToUpdate=new List<Id>();
        system.debug('--serviceEntityIds--'+serviceEntityIds);
        List<Service_Entity__c> recordsToProcess=[Select Name, Id,Sync_Status__c,Send_To_TR__c, TR_Customer_Code__c,TR_Customer_Id__c,GP_Customer_Accounting_Code__c,CurrencyISOCode,
                                                  AcquisitionDB__c,Customer_Name__c,Legal_Entity__c,Sub_Branch__c,Accountrep__c,
                                                  NextRateIncrease__c,LeadSource__c,Account_Industry__c,DiscontinueService__c,
                                                  Taxable__c,TaxCode__c,Delivery_Contact__c,Delivery_Address__c,Delivery_Address_2__c,
                                                  Delivery_Contact_Phone__c,Delivery_Contact_Email__c,Delivery_State__c,Delivery_City__c,
                                                  Delivery_Postal__c,Billing_Contact__c,Billing_Address__c,Billing_Address_2__c,Billing_Contact_Phone__c,
                                                  Billing_Contact_Email__c,Billing_State__c,Billing_City__c,Billing_Postal__c,PO_Number__c,
                                                  Billing_Group__c,Breach_Reporting_Services__c,Admin_Fee_V4__c,Online_Tools__c,Billing_Dept__c,
                                                  Information__c,Customer_Notes__c,Operations_Note__c,Display_as_a_pop_up_note__c,Conversion_Services__c,
                                                  HC_Storage__c,Shredding__c,Software__c,Media_Vault__c,AcctPrefixCode__c,TR_Account_Status__c,TR_NextRateIncrease__c,
                                                  Sub_Branch__r.Sub_Branch_Code__c
                                                  from Service_Entity__c where id in : serviceEntityIds and Send_To_TR__c=True and Sync_Status__c!='Error'];
        system.debug('--Before Try--');
        try{
        //get the records, added couple of more fields which are being used down
        system.debug('--Before For--');
        for (Service_Entity__c se1 : recordsToProcess)
        {
        system.debug('--Inside For--');
            string reqXML=createXMLforServiceEntity(se1);
            system.debug('--ServiceEntity--reqXML--' +reqXML);    
            
            HttpResponse response;
            //LockSERecord(recordsToProcess);
            if ((se1.TR_Customer_Id__c==null || se1.TR_Customer_Id__c=='0') && se1.Send_To_TR__c==True)
            { 
                system.debug('------before insertTR is called');
            response=insertTR(reqXML,'E'); 
                system.debug('------after insertTR is called');
            }
            else if ((se1.TR_Customer_Id__c<>null || se1.TR_Customer_Id__c<>'0') && se1.Send_To_TR__c==True)
            {
            system.debug('------before updateTR is called');    
            system.debug('--Userinfo.getName()---'+Userinfo.getName());    
            response=updateTR(reqXML,'E'); 
            system.debug('after updateTR is called');
            }    
            
            // Parse the JSON response
            // 400 bad request
            // 200 success
            String respText=response.getBody();
            if (response.getStatusCode() != 200) {
                syncStatus='Error';
                syncErrorMessage=respText.substringBetween('<ErrorMessage>','</ErrorMessage>');
                System.debug('The status code returned was not expected: ' +
                             response.getStatusCode() + ' ' + response.getStatus());
                system.debug('syncStatus:'+syncStatus); 
            } else {
                System.debug(response.getBody());
                if (response.getStatusCode() == 200){
                    system.debug('---' + response.getStatusCode() + ' ' + response.getStatus());
                    trCustomerCode=respText.substringBetween('<TRCustomerCode>', '</TRCustomerCode>');
                    trCustomerId=respText.substringBetween('<TRCustomerId>', '</TRCustomerId>');
                    syncErrorMessage='';
                    syncStatus='Synced';
                    system.debug('trCustomerCode:'+trCustomerCode);
                    system.debug(' trCustomerId:'+ trCustomerId);
                    system.debug('syncStatus:'+syncStatus); 
                    se1.TR_Customer_Code__c=trCustomerCode;
                    se1.TR_Customer_Id__c=trCustomerId;
                    se1.Sync_Status__c=syncStatus;
                    
                  //lstServiceEntitiesToUpdate.add(se1.Id);  
                }
                //Method to update this record with the values from the response
                updateSERecord(se1.Id,trCustomerCode,trCustomerId,syncStatus);
                
            }
            
        }

        }
        catch(Exception e){ 
            System.debug('Exception:'+e.getMessage());
        } 
          
         UnLockSERecord(recordsToProcess);
    }
    //method to get token
    public static string getToken()
    {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(tokenUrl);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        String jsonBody ='username=' + 'user1' + '&password=' + '12345';
        request.setBody(jsonBody);
        request.setHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
        HttpResponse response = http.send(request);  

        String respText=response.getBody();
        String respToken=respText.substringAfter('access_token');
        
        //System.debug('---respToken---' + respToken);
        String respToken1=respText.substringBetween('access_token', 'token_type');
        String respToken2=respToken1.replace('":"','');
        String respToken3=respToken2.replace('","','');
   
        System.debug('--respToken3--' +respToken3);  
        
        return respToken3;    
    }
    //new method to create XML for Service entity
    public static string createXMLforServiceEntity(Service_Entity__c se1){
        String ZeroOne='';
        string seReq='';
        seReq=seReq+'<ServiceEntity>';
        seReq=seReq+'<ServiceEntityID>' + se1.Id+'</ServiceEntityID>';
        seReq=seReq+'<ServiceEntityCode>' + se1.Name+'</ServiceEntityCode>';
        seReq=seReq+'<TRCustomerCode>' + se1.TR_Customer_Code__c+'</TRCustomerCode>';
        //seReq = seReq.replace('null','');
        seReq=seReq+'<TRCustomerId>' + se1.TR_Customer_Id__c+'</TRCustomerId>';
        seReq=seReq+'<CustomerName>' + se1.Customer_Name__c+'</CustomerName>';
        //seReq=seReq+'<SubBranch>' + se1.Sub_Branch__c+'</SubBranch>';
        //seReq = seReq.replace('null','');
        seReq=seReq+'<SubBranchCode>'+se1.Sub_Branch__r.Sub_Branch_Code__c+'</SubBranchCode>';
        If (se1.AcctPrefixCode__c<>'-')
        {
        seReq=seReq+'<AccountPrefixCode>' + se1.AcctPrefixCode__c+'</AccountPrefixCode>';
        }
        else
        {
        seReq=seReq+'<AccountPrefixCode>MA-8</AccountPrefixCode>';
        }    
        //seReq = seReq.replace('-','MA-8');
        seReq=seReq+'<GPCustomerAccountingCode>' + se1.GP_Customer_Accounting_Code__c+'</GPCustomerAccountingCode>';
        seReq=seReq+'<Currency>' + se1.CurrencyISOCode+'</Currency>';
        //List<acquisition__c> a; //acquisition__c a;
        List<acquisition__c> a=[select name from acquisition__c where id=:se1.AcquisitionDB__c Limit 1];        
        If (a.size()==0)
        {
        seReq=seReq+'<Acquisition></Acquisition>';     
        }
        else{
            seReq=seReq+'<Acquisition>' + a[0].Name+'</Acquisition>';}
  
        string LineOfBusiness='';
               
        seReq=seReq+'<LinesofBusiness>' + LineOfBusiness+'</LinesofBusiness>';
        seReq=seReq+'<LegalEntity>' + se1.Legal_Entity__c+'</LegalEntity>';
        
        List<User> c3=[select name from User where id=:se1.Accountrep__c Limit 1];

        If (c3.size()==0){
        seReq=seReq+'<AccountRep></AccountRep>';
        }
        Else
        {seReq=seReq+'<AccountRep>' + c3[0].Name+'</AccountRep>';
        }
        //seReq=seReq+'<AccountRep>' + se1.Accountrep__c+'</AccountRep>';
        seReq=seReq+'<AccountStatus>' +se1.TR_Account_Status__c+'</AccountStatus>';

        seReq=seReq+'</ServiceEntity>';    
        seReq = seReq.replace('null',''); 
        return seReq;
    }
        //method to make the call to TR and submit the request
    public static httpresponse insertTR(String Reqxml, String Type)
    {
              String token=getToken();  
            system.debug('token---'+token);
            String header1='Bearer '+token;
            Http http1 = new Http();
            HttpRequest request1 = new HttpRequest();
        If (Type=='E')
        {system.debug('before create Account///');
            request1.setEndpoint(url1);
        system.debug('after create Account///');}
        else If (Type=='D')
                    {system.debug('before create Department////');
            request1.setEndpoint(url12);
        system.debug('after create Department////');}
         else If (Type=='S')        {system.debug('before create Site///');
            request1.setEndpoint(url13);
        system.debug('after create Site///');}
            request1.setMethod('POST');
            //request1.setHeader('Content-Type', 'application/json;charset=UTF-8');
            
            request1.setHeader('Authorization',header1);
            request1.setHeader('Accept', 'application/xml');
            request1.setHeader('Content-Type', 'application/xml');
            
            //string reqXML=createXMLforServiceEntity(se1);
            system.debug('---reqXML--' +ReqXML);
            request1.setBody(ReqXML);
            request1.setTimeout(60000);
            If (test.isRunningTest())
            {
                //write the code for response
                
            }
        Else{//once u generate the fake response uncomment the 238 and comment 240
            //HttpResponse response1 = http1.send(request1);  
            }   
            HttpResponse response1 = http1.send(request1);
        
            System.debug('--response1.getStatusCode() + -- + response1.getStatus()'+response1.getStatusCode() + ' ' + response1.getStatus());
            System.debug('---response1.getBody--' +response1.getBody());
            return response1;
    }
    public static httpresponse updateTR(String Reqxml,String Type)
    {
              String token=getToken();  
            //system.debug('token---'+token);
            String header1='Bearer '+token;
            Http http1 = new Http();
            HttpRequest request1 = new HttpRequest();
        If (Type=='E')
        {   system.debug('before update Account'); 
            request1.setEndpoint(url14);//?_HttpMethod=PATCH');
        system.debug('after update Account');}
        else If (Type=='D')
                    {system.debug('before update Department');
            request1.setEndpoint(url15);
        system.debug('after update Department');}
         else If (Type=='S')        {system.debug('before update Site');
            request1.setEndpoint(url16);
        system.debug('after update Site');}    
        //request1.setHeader('X-HTTP-Method-Override','PATCH');
        request1.setMethod('PUT');
       //request1.setMethod('PATCH');
            //request1.setHeader('Content-Type', 'application/json;charset=UTF-8');
            
            request1.setHeader('Authorization',header1);
            request1.setHeader('Accept', 'application/xml');
            request1.setHeader('Content-Type', 'application/xml');
            
            //string reqXML=createXMLforServiceEntity(se1);
            system.debug('---reqXML--' +ReqXML);
            request1.setBody(ReqXML);
            //request1.setTimeout(10000);
            HttpResponse response1 = http1.send(request1);  
            System.debug('--response1.getStatusCode() + -- + response1.getStatus()'+response1.getStatusCode() + ' ' + response1.getStatus());
            System.debug('---response1.getBody--' +response1.getBody());
            return response1;
    }
    //Lock the submitted record so that no one can edit.
    public static void LockSERecord(List<Id> recordsToProcess1)
    {
                //Lock the record from editing
        Approval.LockResult[] lrList = Approval.lock(recordsToProcess1, false);
        for(Approval.LockResult lr : lrList) { 

           if (lr.isSuccess()) 
        { 
         // Operation was successful, so get the ID of the record that was processed 
         System.debug('Successfully locked SE with ID: ' + lr.getId()); 
           } 
           else { 
         // Operation failed, so get all errors         
         for(Database.Error err : lr.getErrors()) { 
               System.debug('The following error has occurred.');           
               System.debug(err.getStatusCode() + ': ' + err.getMessage()); 
               System.debug('SE fields that affected this error: ' + err.getFields()); 
             } //for end
           } // else end
         } // main for end
        
        //End Locking process
    }
//unLock the submitted record after successful response code.
    public static void UnLockSERecord(List<Service_Entity__c> recordsToProcess1)
    {
                //Lock the record from editing
        Approval.unLockResult[] lrList = Approval.unlock(recordsToProcess1, false);
        for(Approval.unLockResult lr : lrList) { 

           if (lr.isSuccess()) 
        { 
         // Operation was successful, so get the ID of the record that was processed 
         System.debug('Successfully unlocked SE with ID: ' + lr.getId()); 
           } 
           else { 
         // Operation failed, so get all errors         
         for(Database.Error err : lr.getErrors()) { 
               System.debug('The following error has occurred.');           
               System.debug(err.getStatusCode() + ': ' + err.getMessage()); 
               System.debug('SE fields that affected this error: ' + err.getFields()); 
             } //for end
           } // else end
         } // main for end
        
        //End unLocking process
    }
    
    //method to update the SE record that got the response from API call
    @future
    public static void updateSERecord(Id ids,string trCustCode, string trCustId, string syncstatus)
    {
      List<Service_Entity__c> se2=[Select id from Service_Entity__c where id = :ids];  
      for (Service_Entity__c se3 : se2 )
        {  
      se3.TR_Customer_Code__c=trCustCode;
      se3.TR_Customer_Id__c=trCustId;
      se3.Sync_Status__c=syncstatus;
      update se3;      
        }
        
    }

--------------------------------------------
Here is the error i am getting
---------------------------------------------
Future method cannot be called from a future or batch method: synchSEDeptSitesToTR.syncSEToTR(List<String>)
---------------------------------------------

Kindly guide me in fixing this issue.

Thanks
Rao
  • July 20, 2019
  • Like
  • 0
Hi developer,
I have a doubt regarding to filtering the SOQL query.
I have a three set of id's that is:
Set<id> source;
Set<id>destination;
Set<id> sharedserver;(contains id of source and destination as well)
I have wrote query 
baselist=[select id ,name from base element where id in:sharedserver And( not in:source And not in: destination)]

but its not giving exact output. Can anyone help me out?
Thanks.
Hi All Veterans
We have a requirement wherein we have to write a trigger on contact after update. There will be a field called IsDeleted in contacts, when that field will be selected the contact will automatically get associated with a private account. Now the challenge is we have to create the  private account dynamically. Before associating the contact we have to check if that pfivate account contains 10000 contacts if yes then create a new private account and associate that contact with the newly created private account else with the previous account, this process will continue.

Thanks in advance...:)
How do you write an Apex unit test for logic that involves a time-based workflow rule? For example, a user sets a Case status = 'Completed' (soft close). Then a time-based workflow rule sets the status = 'Closed', and a beforeUpdate trigger saves the status only if all child Cases have status = 'Closed'. 

Hi,

I am trying to show a footer with navigation buttons on this lwc when the "currentStep" attribute reaches 5. This child component gets the number of "currentStep" from the parent. Once the 'Next' button is pressed, I want it to change the number to 6. I can't figure out how to send the change in number of 'currentStep' to the parent component.

shortened version of lwc.html - 

<footer class="slds-modal__footer slds-modal__footer_directional">
     <div if:true={currentStepCheck}>
            <lightning-button  variant="neutral" label="Back" icon-name="utility:back" icon-position="left"  title="Back" onclick={moveBack}>
            </lightning-button>
            <lightning-button variant="brand"  label="Next" icon-name="utility:forward  icon-position="right" title="Next" onclick={moveNext}>
            </lightning-button>
      </div>
</footer>
shortened lwc.js
import { LightningElement, api} from 'lwc';

export default class PtmForWizard extends LightningElement {
    @api recordId;
    @api parentId;
    @api currentStep;

    currentStepCheck(){
        this.currentStep = '5';
    }
    moveNext(){
         this.currentStep = '6';
    }
      moveBack(){
        this.currentStep = '4';
   }
}
shortened parent.cmp
<aura:component  implements="flexipage:availableForRecordHome,force:hasRecordId,flexipage:availableForAllPageTypes,force:lightningQuickAction,force:appHostable" access="global"> 
    <aura:attribute name="recordId" type="Id"/>
    <aura:attribute name="parentId" type="Id"/>
    <aura:attribute name="currentStep" type="String" default="1"/>

    <aura:registerEvent name="recordUpdated" type="c:selectedsObjectRecordsEvent"/>

     <force:recordData aura:id="record"
                      layoutType="FULL"
                      recordId="{!v.recordId}"
                      targetRecord="{!v.record}"
                      targetFields="{!v.efRecord }"
                      mode="VIEW"/>

     <div class="{!v.currentStep == '5' ? 'slds-show' : 'slds-hide'}" >
             <c:ptmForWizard recordId="{!v.efRecord.jstcl__PlacementTeamMember__c}" aura:id="childCmp5" parentId="{!v.recordId}" currentStep="{!v.currentStep}"/>
      </div>
</aura:component>
shortened parent.js

 
Hi All, 

I have created a trigger to prevent the deactivation of a user if they own any Accounts, Contacts or unconverted leads - as this causes issues with the Pardot sync (the Marketing team lead me to believe)

The trigger works as expected, though I'm aware that with containing SOQL queries within the FOR loop I'm breaking best practice - but would there be a performance issue on taking this out of the loop and running them on every update (even when they are not needed)

Constructive criticism welcomed

Thanks
 
//Trigger to prevent deactivation of user if they own any records referenced by Pardot.
//Deactivating a user while they still own these records (accounts, contacts, uncoverted leads) will cause issues with Pardot sync

trigger UserPreventDeactivation on User (before update) {
  
    for(User u : Trigger.new){
        User oldU = Trigger.oldMap.get(u.Id);  
        
        //Check if user has changed from active to inactive
        if(!u.IsActive && oldU.IsActive){
            
            //Query number of Accounts, Contacts and Unconverted Leads in User's Name
        	//SHOULD BE OUTSIDE OF LOOP TO BE BULKIFIED? but don't want to run these queries on every update to user if not needed.
        	//but as have only internal users, not likely to deactivate users in bulk
        	Integer contactCount = [SELECT count()
                                      FROM Contact
                                     WHERE ownerId = :u.id
                                     LIMIT 1]; 
        	Integer accountCount = [SELECT count()
                                      FROM Account
                                     WHERE ownerId = :u.id
                                     LIMIT 1];
        	Integer leadCount = [SELECT count()
                                   FROM Lead
                                  WHERE ownerId = :u.id
                                    AND isConverted = FALSE
                                  LIMIT 1];
            
            //add error to screen alerting user
            if( (contactCount + accountCount + leadCount) > 0){
            	u.addError('This user may own accounts, contacts, or unconverted leads.' +
                          'Ensure that these records are transferred to a different owner ' +
                          'before deactivating this user. This is due to issues it will cause ' +
                          'with the Pardot sync.');    
            }     
        }
    }
}



 

The code is with before insert, and I need tb before updating the code run. But when I use the Before update the code works incorrectly, it blocks everything.


trigger ReservDuplicateDate on Reserva__c (before insert) {
    
    for(Reserva__c a:Trigger.new)
    {
        List<Reserva__c> lista=new List<Reserva__c>([Select ID,Data_de_terminio__c,Data_de_inicio__c,sala__c,Orador__c from Reserva__c]);
        for(Reserva__c existentes:lista){
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c &&
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
            }
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c && a.Data_de_terminio__c >= existentes.Data_de_inicio__c ) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
            }
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c && a.Data_de_inicio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
            }
           
            if(a.sala__c == existentes.sala__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c ) {
                a.adderror('Reserva Ja existente na sala com a mesma data!');
                           
            }
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c &&
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c <= existentes.Data_de_terminio__c && a.Data_de_terminio__c >= existentes.Data_de_inicio__c ) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c >= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c && a.Data_de_inicio__c <= existentes.Data_de_terminio__c) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }
           
            if(a.Orador__c == existentes.Orador__c && a.Data_de_inicio__c <= existentes.Data_de_inicio__c && 
               a.Data_de_terminio__c >= existentes.Data_de_terminio__c ) {
                a.adderror('Esse Orador ja esta em cargo de uma reserva!');
            }

        }
    }
    
}
 
hi, I have to write a test class for controller extension. How we apply best practice about bulking in this case? Controller extension constructor takes one standard controller instance. Do i have to instantiate for 200 Times the controller extension in test class? Thank you in advance 
Hi All

I am trying to use lightning out functionality to embed my ligthning component on some public webistes and i want it should be used there only.

Please let me know if there is any way to restrict the usuage to same.
Hi...

I'm calling a controller function in the client - side from blur event in the component.

component code 
<div class="slds-form-element slds-grid slds-wrap">
                                    <div class="slds-form-element__control slds-grow">
                                        <ui:inputText class="slds-input inputFieldWidth"
                                                      labelClass="slds-form-element__label slds-form-element__label_edit slds-no-flex"
                                                      aura:id="inputId"
                                                      blur ="{!c.closeNameBox}"
                                                      change="{!c.onNameChange}"
                                                      maxlength="17"
                                                      required="true"
                                                      label="Tracking #"
                                                      value="{!v.singleRec.Shipping_Track_Number__c}" />
                                    </div>
                                </div>

In the controller:
onNameChange : function(component,event,helper){ 
        // if edit field value changed and field not equal to blank,
        // then show save and cancel button by set attribute to true

        if(event.getSource().get("v.value").trim() != ''){ 
            component.set("v.showSaveCancelBtn",true);

        }

    },   
    
    closeNameBox : function (component, event, helper) {

      // on focus out, close the input section by setting the 'nameEditMode' att. as false   
        component.set("v.nameEditMode", false); 
      // check if change/update Name field is blank, then add error class to column -
      // by setting the 'showErrorClass' att. as True , else remove error class by setting it False   

        if(event.getSource().get("v.value").trim() == 0){
            component.set("v.showErrorClass",true);
        }else{
            component.set("v.showErrorClass",false);
        }
    }

I got the error: Cannot read property 'trim' of undefined. So, the event.getSource() return undefined...

Note: The <input... component is inside a <aura:iteration... so the aura:id="inputId" is the same for all input. I don't know if this is the reason for the error.

Please, let me know if you need more code...

Thanks,


 
I have a custom button in lightning and whenever user clicks that, whoever clicks should be assigned with his namee. what is the query that i should use in Apex controller
how to know who who worked on how many cases
I want to auto-populate the standard 'Lead Source' (picklist) field with a part of the string stored in another field called the Source Tracking Code. The Source Tracking Code looks something like this -- Offline>TradeShow>SHRM2018>>

For this I have created an Apex class to break the string into parts and then search for the part which matches the picklist values. Please note that I have created a custom picklist field Lead Source3 (using instead of Lead Source) for Testing


public class LeadSource {

public static void LeadSource(){
List<Lead> l = new List<Lead>();

for(Lead ls:l)
{
String alpha = ls.Manticore_Full_Promotion_Code__c;
List<String> lstAlpha = alpha.split('>');

Set<String> convertInSet = new Set<String>(lstAlpha);

String FinalValue;

if(convertInSet.contains('401k Exchange')){
    FinalValue = '401k Exchange';
}
else if(convertInSet.contains('Affiliate')){
    FinalValue = 'Affiliate';
}
else if(convertInSet.contains('Bing')){
    FinalValue = 'Bing';
}


ls.Lead_Source3__c = FinalValue;

}
 

}
}


After this I created a Trigger to run this Apex class as below

trigger LeadSource on Lead (before insert, before update) {


for(Lead myLeads:Trigger.new){

LeadSource.LeadSource();
}
}

I am new to Programming and to Salesforce, could somebody please help me figure out why I am not able to get anything populated on the Laed Source3 field.

Thanks,
Tanushree
 

Hi All,

I am trying to update a custom field (NetNewLead__c) when a Lead's Email doesn't exist in Contact Email.

I am thinking a Trigger is the best solution, but my Apex skills are lacking.

I do not want to prevent creation of the Lead.

Can someone take a look at my code and offer advice?

Kind regards,

Robert

Code is below

trigger NetNewLead_Trigger on Lead (after update) {
    class UniqueKey {
        UniqueKey(String email) {
        this.email = email;
        }
        string Email;
        integer hashCode() {
            return toString().hashCode();
        }
        boolean equals(Object o) {
            return toString() == ((UniqueKey)o).toString();
        }
        public override string toString() {
            return String.format(
                'Email = \'\'{0}\'\'',
                new String[] {
                Email==null?'':String.escapeSingleQuotes(Email.tolowercase())
                }
            );
        }
    }

    Map<UniqueKey, Lead> leads = new Map<UniqueKey, Lead>();
    for(Lead record:Trigger.new) {
        if(record.isconverted) {
            UniqueKey key = new UniqueKey(record.email);
            if(leads.containskey(key)) {
                record.addError('Duplicate lead conversion.');
            } else {
                leads.put(key, record);
            }
        }
    }
    String[] keys = new String[0];
    for(UniqueKey key:leads.keyset()) {
        keys.add(key.tostring());
    }
    String query = string.format(
        'SELECT Id,Email,RecordTypeId FROM Contact WHERE RecordTypeId =:Client Contact" and {0}',
        new String[] {
            String.join(keys, ' OR ')
        }
    );
    if(!leads.isempty()) {
        for(Contact record:Database.query(query)) {
            UniqueKey key = new UniqueKey(record.email);
            if(leads.containskey(key)) {
                leads.get(key).addError('Duplicate lead conversion.');
            }
        }
    }

}

My requirement is to be able to import quote line items into a quote using a CSV. I have written the following code but I'm unable to get it working. The code shows no errors but when I try to import a CSV, it doesn work. Thank you in advance for any guidance you can provide:

APEX Code:
public class importDataFromCSVController {
	public Blob csvFileBody{get;set;}
	public string csvAsString{get;set;}
	public String[] csvFileLines{get;set;}
	public List<QuoteLineItem> quoteLineItemList{get;set;}
    public List<Quote> quoteNumberList{get;set;}
  	public importDataFromCSVController(){
    
    csvFileLines = new String[]{};
    quoteLineItemList = New List<QuoteLineItem>(); 
  	}
  
  	public void importCSVFile(){
      List<String> allProductCodes = new List<String>();
      List<String> allQuoteNumbers = new List<String>();
      Map<String, Id> quoteNumber = new Map<String, Id>();
      
      //Query for Products that have matching Product Code
      Map<String, Id> productCode = new Map<String, Id>();
      for (Product2 p : [SELECT Id, Name from Product2 where Name in :allProductCodes LIMIT 1]) {
          productCode.put(p.Name,p.Id);
      }
      
      //Query for Quotes that have matching Quote Number
      Map<String, Id> quoteNum = new Map<String, Id>();
        for (Quote q : [SELECT Id, QuoteNumber from Quote where QuoteNumber in :allQuoteNumbers LIMIT 1]) {
            quoteNum.put(q.QuoteNumber, q.Id);
      }
      
      // Set the Product Id for each Product Code  
      for(Integer j=0;j<quoteLineItemList.size();){
          QuoteLineItem qli1;
          Id Productid = productCode.get(allProductCodes[j]);
          if (Productid != null) {
              qli1.Product2.Id = Productid;
          }
      // Set the Quote Id for each Quote
          for (Integer z=0;z<quoteNumberList.size();){
              Quote q1;
              Id quoteNumberId = quoteNum.get(allQuoteNumbers[z]);
              if (quoteNumberId != null) {
                  q1.Id = quoteNumberId;
              }
          }    
      }
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           for(Integer i=1;i<csvFileLines.size();i++){
               QuoteLineItem lineItem = new QuoteLineItem() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               allQuoteNumbers.add(csvRecordData[0]);
               allProductCodes.add(csvRecordData[1]);
               lineItem.Quantity = decimal.valueof(csvRecordData[2]);
               lineItem.UnitPrice = decimal.valueof(csvRecordData[3]);
               lineItem.Global_Discount__c = decimal.valueof(csvRecordData[4]);                                                                    
               quoteLineItemList.add(lineItem);   
           }
        insert quoteLineItemList;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please try importing the file again');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Visualforce Page Code
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="5"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Quote Line Items" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!quoteLineItemList}" var="acc">
              <apex:column value="{!acc.Quote}" /> 
              <apex:column value="{!acc.Product2}" />
              <apex:column value="{!acc.Quantity}" />
              <apex:column value="{!acc.UnitPrice}" />
              <apex:column value="{!acc.Global_Discount__c}" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

 
Hi All ,


Here my requirement is while creting a record i need required field and updaing the same record i don't want required field.

Example:
I) I Have one custom object Employee__c and field is DOB.Now  while creating a record i need required field , if value is not there , then it showing required value is missing
 2) I want update on same record then i have remove value from DOB field at that time i don't want required value.

Please suggest me, how can achive with example code.


Thanks in Advance.
Chinna
I have to remove javascript buttons to adapt it to lightning experience (LE).
I have created a custom button to create a new record, and like the new record has to receive some values from the related one, I do it with url hack, as the js button did it.
The button run perfect in classic, sending the values to the new record, but in LE the create record page opens, but not shows none of the sended values from the related record.
There exists some form to do it?
I know I would should use a quick action to create the new record in LE, but in some cases I need to change the values passed in function of the values of the related record, and I don´t know if this is possible with quick actions (ex: the record type of the new record depends of the profile of the user who creates it).
Hi,

In LWC, on the component load, I am fetching the latitude and longitude of the logged in user and trying to display it on the component. I have created two attributes named lat and lng and marked it with @track decorator so that whenever the value of these attributes is changed, the component will rerender automatically. I am setting the value of these attributes in connectedCallback, but the updated value is not getting reflected on the component. Below is the html and js files.
 
<template>
    <div class="slds-box">
        <div class="slds-text-heading--large">Weather Report - {lat} {lng}</div>
    </div>
</template>
 
import { LightningElement, track } from 'lwc';

export default class WeatherAppContainer extends LightningElement {
    @track lat;
    @track lng;
    connectedCallback() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
        
        function showPosition(position) {
            console.log("position: ",position);
            console.log("position coords: ",position.coords);
            console.log("position coords lat: ",position.coords.latitude);
            this.lat = position.coords.latitude; 
            this.lng = position.coords.longitude; 
            console.log("lat: ",this.lat);
            console.log("lng: ",this.lng);
        }
    }

}

The console "position coords lat" prints the value correctly, but the next console statment does not get printed. I am guessing that we cannot use this keyword in the connectedCallback. Any pointers how to solve this? Thanks.
Hi,

Need inputs on how to parse below string and extract all the relevant information such as Source, Name etc.

Source: Web Visitor 
Name: Ravi Sharma 
Age of primary applicant: 9 


Email: test@yahoo.com 
Phone: 1234567 
Address: 10th Street 
City: Woodstock 
State: GA 
Comments: Test Comments 
Winter 19 release has brought this new tag - lightning:map to show google maps in lightning maps. I am trying to implment below example in my dev org, but the map marker is not showing up on the org.

Example given here:https://developer.salesforce.com/docs/component-library/bundle/lightning:map/example

When I check the broswer console, I can see below error:

util.js:218 Google Maps JavaScript API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
lw.j @ util.js:218
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:183
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:76
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:73
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:76
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:164
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:76
(anonymous) @ js?key=&callback=LightningPrimitiveMap.init:164
Ee @ js?key=&callback=LightningPrimitiveMap.init:75
Ae.xa @ js?key=&callback=LightningPrimitiveMap.init:164
(anonymous) @ stats.js:1
util.js:218 Google Maps JavaScript API warning: InvalidKey https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key

Question1: Do we need to explicitly add google map api key? Only then the map would work? I am assuming that Salesforce should automatically take care of this?
Question 2: If the answer to above question in yes, then how do we add the api key? I have a developer key, but not sure how to add it.
Hi,

I am trying to configure SSO between Salesforce and Ringcentral. When I login to Ringcentral using the SSO option, it redirects me to the Salesforce error screen. On checking the SAML trace, I can see below error:

GET https://domain-name.my.salesforce.com/_nc_external/identity/saml/SamlError?idpError=1605 HTTP/1.1

Any pointers on how to resolve this?

 
It seems that there is a bug with lightning:input type="datetime-local" tag. When I add this tag in my component, thenchoose a date and time using the date time selector and try to save the record to database, apex is not able to take the value? Any pointers on how to save this value to a date time field present on an object. Below is the sample code I am trying to implement:

dateTimeLocal.cmp
 
<aura:component controller="DateTimeLocalCtrl">
    <aura:attribute name="lead" type="Lead" default="{'sobjectType':'Lead','id':'00Q9000001BtwNE'}"/>
	<lightning:input type="datetime-local" label="Start" name="Start" value="{!v.lead.Start__c}"/>
    <lightning:button label="Save" iconName="utility:save" onclick="{!c.doSave}"/>
</aura:component>
dateTimeLocalController.js
({
	doSave : function(component, event, helper) {
		
       var action = component.get("c.upsertLead");
        var lead = component.get("v.lead");
        console.log("*****Date: "+component.get("v.lead.Start__c"));
        // set param to method  
        action.setParams({
            'ld': lead
        });
        // set a callBack    
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log("*****Success");
            }else{
                console.log("*****Failure");
            }
        });
        // enqueue the Action  
        $A.enqueueAction(action);
	}
})

DateTimeLocalCtrl.apxc
public class DateTimeLocalCtrl {

    @AuraEnabled
    public static Lead upsertLead(Lead ld){
        upsert ld;
        return ld;
    }

}


 
The convertTimeZone() does not work properly between 12am to 1pm. It gives the output for the previous day. My user is in (GMT+10:00) Australian Eastern Standard Time (New South Wales) (Australia/Sydney) timezone and when the time in this timezone is between 12am to 1am, the SOQL query gives incorrect results:

SELECT Id FROM Activity__c WHERE DAY_ONLY(convertTimeZone(Activity_Closed_Date_Time__c)) =: Date.today() 
 
I have a action support inside a apex command link which is present inside a page block table. The action support in not calling the apex method.

 
<apex:column headerValue="Call Attempt">
                        <apex:commandLink>{!cmpgnMember.Call_Attempt__c}
                        	<apex:actionSupport action="{!createCallReport}" event="onclick" />
                        </apex:commandLink>
</apex:column>
 
public PageReference createCallReport(){
        System.debug('******contactId: ');
        return null;
}

 
On the Manage Members standard page, there is a filter as shown in image below:

User-added image

Any idea how do we handle conditions such as starts with, contains, does not contain in SOQL?
I have 2 functions in my JS helper - getLatLng and getResponse. getLatLng gets the current location of the user and sets two attributes in the component namely lat and lng. getResponse uses these two attributes for further processing. I am calling both these functions from my JS controller one after the other. The problem is that getResponse gets called even before the execution of getLatLng is completed. Is there any way to set a callback so that when getLatLng sets the lat and lng on component, then only getResponse is called? Here is the code for JS controller and  JS helper.

WeatherController.js
 
({
    doInit : function(component, event, helper) {
        helper.getLatLng(component);
        helper.getResponse(component);
    }
})
WeatherHelper.js
({
    getResponse : function(component){
        var action = component.get("c.getCalloutResponseContents");
        var lat = component.get("v.lat");
        var lng = component.get("v.lng");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=' +lat+ '&lon=' +lng+ '&appid=9b2719bd93477d05ad2575ccb81cb666&units=metric'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.response", JSON.parse(response.getReturnValue()));
            }
        });
        $A.enqueueAction(action);
    },
    
    getLatLng : function(component) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                component.set("v.lat", position.coords.latitude);
                component.set("v.lng", position.coords.longitude);
            });
        } 
    }
    
})
Thanks in advance for your help.
I am trying to build a lightning component which will display the weather condition of a particular area. For getting the weather details, I am making a webservice callout. In Weather.cmp component, I have defined a handler for the init event. So as soon as the page is loaded, the init handler gets executed, and calls a method which is present in my Apex controller named WeatherCtrl which makes a webservice callout and returns the response. I have debug statments in my Apex controller and I see that the response is coming in the Apex controller. But when I return the response from my JS helper - WeatherHelper.js, the response.getReturnValue() seems to be null. 
Any ideas what I may be doing wrong here. Here is the code:

Weather.cmp
 
<aura:component controller="WeatherCtrl">
	
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <aura:attribute name="response" type="WeatherResponse"/>
    
    Longitude : <ui:outputText value="{!v.response.coord.lon}"/>
    
</aura:component>

WeatherController.js
 
({
	doInit : function(component, event, helper) {
		helper.getResponse(component);
	}
})

WeatherHelper.js
 
({
	getResponse : function(component) {
		var action = component.get("c.getCalloutResponseContents");
        action.setParams({
            "url": 'http://api.openweathermap.org/data/2.5/weather?lat=12.971599&lon=77.594563&appid=9b2719bd93477d05ad2575ccb81cb666'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                console.log(response.getReturnValue());
                component.set("v.response", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
	}
})

WeatherCtrl.apxc
 
public class WeatherCtrl {
    
    // Pass in the endpoint to be used using the string url
    @AuraEnabled
    public static WeatherResponse getCalloutResponseContents(String url) {
        
        // Instantiate a new http object
        Http h = new Http();
        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        System.debug('*****response: '+WeatherResponse.parse(res.getBody()));
        return WeatherResponse.parse(res.getBody());
    }
    
}

WeatherResponse.apxc
 
//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class WeatherResponse{
    public static void consumeObject(JSONParser parser) {
        Integer depth = 0;
        do {
            JSONToken curr = parser.getCurrentToken();
            if (curr == JSONToken.START_OBJECT || 
                curr == JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == JSONToken.END_OBJECT ||
                curr == JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }

    public class Weather {
        public Integer id {get;set;} 
        public String main {get;set;} 
        public String description {get;set;} 
        public String icon {get;set;} 

        public Weather(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'id') {
                            id = parser.getIntegerValue();
                        } else if (text == 'main') {
                            main = parser.getText();
                        } else if (text == 'description') {
                            description = parser.getText();
                        } else if (text == 'icon') {
                            icon = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Weather consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Coord {
        public Integer lon {get;set;} 
        public Integer lat {get;set;} 

        public Coord(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'lon') {
                            lon = parser.getIntegerValue();
                        } else if (text == 'lat') {
                            lat = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Coord consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Wind {
        public Double speed {get;set;} 
        public Double deg {get;set;} 

        public Wind(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'speed') {
                            speed = parser.getDoubleValue();
                        } else if (text == 'deg') {
                            deg = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Wind consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Rain {
        public Integer h3 {get;set;} 

        public Rain(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'h3') {
                            h3 = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Rain consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Clouds {
        public Integer all {get;set;} 

        public Clouds(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'all') {
                            all = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Clouds consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public Coord coord {get;set;} 
    public Sys sys {get;set;} 
    public List<Weather> weather {get;set;} 
    public Main main {get;set;} 
    public Wind wind {get;set;} 
    public Rain rain {get;set;} 
    public Clouds clouds {get;set;} 
    public Integer dt {get;set;} 
    public Integer id {get;set;} 
    public String name {get;set;} 
    public Integer cod {get;set;} 

    public WeatherResponse(JSONParser parser) {
        while (parser.nextToken() != JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != JSONToken.VALUE_NULL) {
                    if (text == 'coord') {
                        coord = new Coord(parser);
                    } else if (text == 'sys') {
                        sys = new Sys(parser);
                    } else if (text == 'weather') {
                        weather = new List<Weather>();
                        while (parser.nextToken() != JSONToken.END_ARRAY) {
                            weather.add(new Weather(parser));
                        }
                    } else if (text == 'main') {
                        main = new Main(parser);
                    } else if (text == 'wind') {
                        wind = new Wind(parser);
                    } else if (text == 'rain') {
                        rain = new Rain(parser);
                    } else if (text == 'clouds') {
                        clouds = new Clouds(parser);
                    } else if (text == 'dt') {
                        dt = parser.getIntegerValue();
                    } else if (text == 'id') {
                        id = parser.getIntegerValue();
                    } else if (text == 'name') {
                        name = parser.getText();
                    } else if (text == 'cod') {
                        cod = parser.getIntegerValue();
                    } else {
                        System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }
    
    public class Sys {
        public String country {get;set;} 
        public Integer sunrise {get;set;} 
        public Integer sunset {get;set;} 

        public Sys(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'country') {
                            country = parser.getText();
                        } else if (text == 'sunrise') {
                            sunrise = parser.getIntegerValue();
                        } else if (text == 'sunset') {
                            sunset = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Sys consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    public class Main {
        public Double temp {get;set;} 
        public Integer humidity {get;set;} 
        public Integer pressure {get;set;} 
        public Double temp_min {get;set;} 
        public Double temp_max {get;set;} 

        public Main(JSONParser parser) {
            while (parser.nextToken() != JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != JSONToken.VALUE_NULL) {
                        if (text == 'temp') {
                            temp = parser.getDoubleValue();
                        } else if (text == 'humidity') {
                            humidity = parser.getIntegerValue();
                        } else if (text == 'pressure') {
                            pressure = parser.getIntegerValue();
                        } else if (text == 'temp_min') {
                            temp_min = parser.getDoubleValue();
                        } else if (text == 'temp_max') {
                            temp_max = parser.getDoubleValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Main consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }
    
    
    public static WeatherResponse parse(String json) {
        return new WeatherResponse(System.JSON.createParser(json));
    }
}


 
I have created a VF page and associated controller to override the standard New Button on lead page. In the controller, I am creating a PageReference and in the url, I am passing a parameter which populates a picklist field present on Lead record. This works fine, the picklist gets populated as expected. Now on the page layout, if I make the picklist field as read-only, the field no longer gets populated. Any hack to populate a read-only field through url params? Attaching the code for reference :

VF Page :
<apex:page standardController="Lead" extensions="LeadFieldsAutoPopulateCtrl" action="{!doRedirect}">
  </apex:page>

Apex Class :
public class LeadFieldsAutoPopulateCtrl {

    public LeadFieldsAutoPopulateCtrl(ApexPages.StandardController stdController){
    
    }
    
    //Method gets called before the Visualforce page gets loaded. It redirects the user to the New Lead detail page.
    public PageReference doRedirect(){
        Pagelayout_FieldNames__c ownerGeographyFieldName = Pagelayout_FieldNames__c.getValues('Lead_OwnerGeographyPicklist');
        String redirectURL = '/00Q/e?retURL=%2F00Q%2Fo&nooverride=1';
        String userId = UserInfo.getUserId();
        List<User> userList = new List<User>();
        if(String.isNotBlank(userId)){
            userList = [SELECT Geography__c FROM User WHERE Id =:userId];
        }
        String userGeography = '';
        if(userList.size() > 0){
            userGeography = userList.get(0).Geography__c;
        }
        if(String.isNotBlank(userGeography) && String.isNotBlank(ownerGeographyFieldName.PagelayoutFieldName__c)) {
            redirectURL = redirectURL + '&' + ownerGeographyFieldName.PagelayoutFieldName__c + '=' + EncodingUtil.urlEncode(userGeography,'UTF-8');
        }
    	PageReference pageRef = new PageReference(redirectURL);
        return pageRef;
    }
}


 
I am trying to create a clone functionality which clones the related list records as well. When I clone an account record, I clone the associated quote records also (Quotes are related to account through AccountId field). The cloned quote record has reference to the old account and I need to update the AccountId field to the new account that is cloned by my code. But since the AccountId field on Quote object is neither createable nor updateable, I am getting an exception. Any solution to this?
Thanks in advance for the help.
Lets say I have Id of Account record and I am initializing the sobject and assigning the Id to account variable. Below is the code :
sObject obj = Schema.getGlobalDescribe().get(parentObjName).newSObject() ;
obj.Id = recordId;
System.debug('****obj : '+obj);
Debug Result: 
****obj : Account:{Id=0019000001dbup5AAA}
I was hoping that the debug will have the entire information from the account example like : Account:{Id=0019000001dbup5AAA, Name=TestAccount,...}
Is there any way to initialize the sobject in a way such that it gets loaded with the entire information?
When we convert a lead, by default the account detail page is opened. I want to open the opportunity detail page if "Do not create a new opportunity upon conversion." checkbox is unchecked.
Is there any way to achieve this through configuration. I do not want to customize the entire lead conversion process for this because I have duplicate rules enabled in my org. And hadling duplicate rules in custom lead conversion will be an effort intensive task.

Thanks,
Ravi
I have DOB (API Name : BirthDate__c) and I want to calculate age in years and months. I have created two formula fields
 
Age in years

FLOOR((TODAY()- BirthDate__c )/365.2425)
 
Age in months (remaining months)

FLOOR(MOD((TODAY()-BirthDate__c),365.2425)/30)

If date of birth is 11 Aug 2013 and todays date is 11 Aug 2015, this gives result as 1 year 12 months. Instead the result should be 2 years 0 months.
I need to open quote standard page with some fields pre-populated. For that I have used URL Hacking (passing parameters in url). This technique works perfectly in browsers but does not work in Salesforce1 app.

Below is the relevant JS code :
 
window.top.location='/0Q0/e?retURL=%2F{!Opportunity.Id}&oppid={!Opportunity.Id}&Name={!Opportunity.Contact_First_Name__c}+{!Opportunity.Contact_Last_Name__c}';

Anyone has a workaround for that?
How to remove Del action link that appears on opportunity line items in a community. The profile of community user has only Read access on opportunity.
How to find associated price book for a given opportunity. For example, when I add a product under opportunity for the first time, it asks me to select a price book. Now in my apex code, I need to check whether a given opportunity already has a related price book or not?

User-added image
Hi,

I am trying to configure SSO between Salesforce and Ringcentral. When I login to Ringcentral using the SSO option, it redirects me to the Salesforce error screen. On checking the SAML trace, I can see below error:

GET https://domain-name.my.salesforce.com/_nc_external/identity/saml/SamlError?idpError=1605 HTTP/1.1

Any pointers on how to resolve this?

 
The convertTimeZone() does not work properly between 12am to 1pm. It gives the output for the previous day. My user is in (GMT+10:00) Australian Eastern Standard Time (New South Wales) (Australia/Sydney) timezone and when the time in this timezone is between 12am to 1am, the SOQL query gives incorrect results:

SELECT Id FROM Activity__c WHERE DAY_ONLY(convertTimeZone(Activity_Closed_Date_Time__c)) =: Date.today() 
 
I've created a lightning component which shows terms and conditions in a modal when I click on button. How can acheive autoscroll on modal?
 
I need to open LWC component when i click on "Edit" button on another LWC component. I have one LWC component with some buttons on case detail page. When i click on the edit button an another edit lwc component should be open with the same record id context.

I have wrote this below function on 'Edit' button onclick LWC.   In url it is coming as "lightning/cmp/c%3AEditCaseButtonOverride" and error This page isn't available in Salesforce Lightning Experience or mobile app.
navigateToEditComponent() {
        this[NavigationMixin.Navigate]({
            "type": "standard__component",
            "attributes": {
                componentName: "c:EditCaseButtonOverride",
                recordId :this.recordId   
            }   
        });
    }



case edit page
Hi,

I am able to cover Trigger.IsInsert & Trigger.IsUpdate but Trigger.IsDelete is not covering. Please check below test class and provide your suggestions.

Trigger:-
trigger CMC_Post_Tention_Weight_Rollup on OpportunityLineItem (after Insert, After Delete, After Update) 
{
Product2 productPostTensionWeight = [select id, name From Product2 where name = 'Post tension'];
    
if(trigger.isInsert)
{
List <OpportunityLineItem> postTensionWeight = trigger.new; //for update/Insert    
List<Id> listOptyIds = new List<Id>(); 
for(OpportunityLineItem eachOptyLineItem : PostTensionWeight ) 
    {
    listOptyIds.add(eachOptyLineItem.OpportunityId); 
    }

List <Opportunity> AllOppty = [Select ID, Name, Total_Post_Tension_Weight__c  from Opportunity 
                               where id in: listOptyIds];
for(Opportunity opty:AllOppty)
    {
    for(OpportunityLineItem PTW : postTensionWeight)
        {
          
        if(PTW.Product2Id == productPostTensionWeight.Id && PTW.OpportunityId == opty.Id)
            {   
            Opty.Total_Post_Tension_Weight__c = Opty.Total_Post_Tension_Weight__c + PTW.Post_Tension_Weight__c;   
            
            }
         }    
     }
update AllOppty;
}

if(trigger.isDelete)
{
List <OpportunityLineItem> postTensionWeight = trigger.Old; //for Delete    
List<Id> listOptyIds = new List<Id>(); 
for(OpportunityLineItem eachOptyLineItem : PostTensionWeight ) 
    {
    listOptyIds.add(eachOptyLineItem.OpportunityId); 
    }

List <Opportunity> AllOppty = [Select ID, Name, Total_Post_Tension_Weight__c  from Opportunity 
                               where id in: listOptyIds];
for(Opportunity opty:AllOppty)
    {
    for(OpportunityLineItem PTW : postTensionWeight)
        {
      
        if(PTW.Product2Id == productPostTensionWeight.Id && PTW.OpportunityId == opty.Id)
            {
           Opty.Total_Post_Tension_Weight__c = Opty.Total_Post_Tension_Weight__c - PTW.Post_Tension_Weight__c;   
            
            }
         }    
     }

update AllOppty;
}

if(trigger.isUpdate)
{
List <OpportunityLineItem> postTensionWeight = trigger.New;
List <OpportunityLineItem> OldpostTensionWeight = trigger.Old;    
List<Id> listOptyIds = new List<Id>(); 
for(OpportunityLineItem eachOptyLineItem : PostTensionWeight ) 
    {
    listOptyIds.add(eachOptyLineItem.OpportunityId); 
    }

List <Opportunity> AllOppty = [Select ID, Name, Total_Post_Tension_Weight__c  from Opportunity 
                               where id in: listOptyIds];
for(Opportunity opty:AllOppty)
    {
    for(OpportunityLineItem PTW : postTensionWeight)
        {
        For(OpportunityLineItem OPTW : OldpostTensionWeight)
        {        
        if(PTW.Product2Id == productPostTensionWeight.Id && PTW.OpportunityId == opty.Id && PTW.ID==OPTW.ID)
            {
      
            Opty.Total_Post_Tension_Weight__c = Opty.Total_Post_Tension_Weight__c - OPTW.Post_Tension_Weight__c + PTW.Post_Tension_Weight__c;   
            
            }
         }
        }     
     }

update AllOppty;
}
   


Test Class:- 

@istest(SeeAllData = true)
public with sharing class testupdateoppty{
 public static testMethod void TestdeletetonneageMethod() 
    {
      Opportunity op3 = new Opportunity(Name='Testoppthhhhhhssssde');
         
      op3.Bid_Date_Time__c = system.today();
      op3.CloseDate = system.today();
      op3.Market_Segment__c = 'Test1';
      op3.Stage_Structural__c = 'Planning';
      op3.State__c = 'AK';
      op3.City__c = 'Test';
      op3.Opportunity_Type__c = 'Test2';             
      op3.Referred_To__c = 'Test3';
      op3.Referred_From__c = 'Test4';
      op3.Sales_Office__c = 'Test6';
      op3.StageName = 'Planning';
      op3.Total_Loose_Dowel_Revenue__c = 1234;
      op3.Total_TBA_Revenue__c = 200000;
      op3.Total_Loose_Dowel_Revenue__c=1000;
      op3.Total_Loose_Dowel_Tons__c= 2000;
      op3.Dummy_Tonnage__c = 23 ;
      insert op3;
      
       Pricebook2 pb1 = [select Id from Pricebook2 where isStandard=true limit 1];                          
       Product2 prod1 = new Product2(Name = 'Loose Dowels123', ProductCode = 'LB');        
       insert prod1;
       
     
       
        PricebookEntry price = new PricebookEntry(
            
            Pricebook2Id = pb1.Id,
            UnitPrice = 1.0,
            IsActive = true,
            Product2Id = prod1.Id
            
            );
            insert price;
       
      
                 
      List<opportunityLineItem> opppro1 = new opportunitylineitem[]{new opportunitylineitem(UnitPrice=10000.00,
      Quantity=10,Total_Revenue__c = 10000.00, opportunityid=op3.id, pricebookEntryId=Price.id, Invoiced__c = TRUE)};
           
            insert opppro1;   
    
    op3.Dummy_Tonnage__c  = 50;
           update op3;
            
          Test.startTest();
           delete op3;
          Test.stopTest();
    }
}
 
Hi,

I need a pop up box to display instructions when when a picklist value is selected. 
On the case object I have a picklist called "Requst Type" which has multiple values however if they select the value "Error Message" I need a pop up that says please ensure you add a screen shot of the error message and provide details of steps to recreate and so on. 
I have created a visualforce page (my first) but that is as far as I got, I dont know if this is even the correct route to take or how to get it to pop up if even possible.
Any advice welcom as this is tottaly new to me. 

Thanks You,

Lorr 
How to get value from Helper.js to Controller.js in Lightning Component
Hi All,

Would the lightning web component available to get the url parameter?

The url rediret everytime when enter salesforce ligthning.

Thank you
Hi,
I am need to to salesforce, I am writing a visualforce page to display check boxes and list of accounts with a process button. Upon slecting the accounts and the check boxes the process button should contain a method which displays the list of contacts related to selected accounts.
I am unable to retrieve the list of contact names using the selected accounts.I am getting an error when i use a soql query to retrieve the contacts using the account id.

Below is my apex code for above requirment.
Please let me know if my question is not clear.


public class accountcontactwrap {
 public list<accountwrap> warpacc{get;set;}
 public list<account> selectedAccounts{get;set;}
 public list<contact> cont{get;set;}
// public list<contactwrap> wrapcon{get;set;}
  public accountcontactwrap(){
   warpacc=new list<accountwrap>();
   for(account ab:[select id,name,phone from account limit 10]){
    warpacc.add(new accountwrap(ab));
   }
  }
  
public void showcontacts(){
cont=new list<contact>();
 for(accountwrap warpobj:warpacc)
 {
  if(warpobj.isSelected==true){
  cont=[select lastname from contact where account.id=warpobj.acc.id];
   
  }
 }
}

 public class accountwrap{
 public account acc{get;set;}
 public boolean isSelected{get;set;}
  public accountwrap(account a){
   acc=a;
   isSelected=false; 
  }
I'm not able to test getters/setters neither understand how it works to test them.
public with sharing class ALSearchController 
{
public class Location{
        @AuraEnabled 
        public String icon{get;set;} 
        @AuraEnabled 
        public String title{get;set;} 
        @AuraEnabled 
        public GeoLocation location{get;set;} 
        @AuraEnabled 
        public String description{get;set;} 
        @AuraEnabled 
        public String id{get;set;} 
        @AuraEnabled 
        public String type{get;set;} 
        @AuraEnabled 
        public String status{get;set;} 
    }
}
I tried 
Location loc = new Location();
String icon = loc.icon;
icon = 'test';
System.assertEquals(icon, 'test');
but I got an error for the = sign : Unexpected token '=' even if the Location object belong to ALSearchController. 

 
I am trying to use an Apex trigger to post billings and apply a cash receipt. I get the error, "Variable does not exist:bill" (it is on the 4th line from the bottom and in bold).
Does anyone have any suggestions?

trigger AcctSeed_CreateiDonateBilling on Opportunity (after insert,after update) {
    for (Opportunity Oppty : Trigger.New){
        IF(Oppty.I_Donate__c == TRUE && Oppty.StageName == 'Pledged'){
   
    // Create billing records to post and unpost
    
    AcctSeed__Billing__c[] billings = new List <AcctSeed__Billing__c> ();
        billings.add(
            new AcctSeed__Billing__c(
                AcctSeed__Date__c = System.today(),
                AcctSeed__Customer__c = Oppty.AccountId,
                AcctSeed__Status__c = 'Approved',
                AcctSeed__Due_Date2__c = System.today() + 30,
                AcctSeed__Opportunity__c = Oppty.Id
                )
            );

    insert billings;

    // Create billing line records to post and unpost
    AcctSeed__Billing_Line__c[] bLines = new List <AcctSeed__Billing_Line__c> ();
    AcctSeed__GL_Account__c glAccount = [Select Id From AcctSeed__GL_Account__c limit 1];
    
    for (AcctSeed__Billing__c bill : billings) {
        AcctSeed__Billing_Line__c objBillingLine = new AcctSeed__Billing_Line__c();
        objBillingLine.AcctSeed__Billing__c = bill.id;
        objBillingLine.AcctSeed__Date__c = System.today();
        objBillingLine.AcctSeed__Rate__c = Oppty.Amount;
        objBillingLine.AcctSeed__Hours_Units__c = 1;
        objBillingLine.AcctSeed__Revenue_GL_Account__c = glAccount.Id;
        bLines.add(objBillingLine);
        }
    
    insert bLines;
        
    // Call the post billings service
    AcctSeed.PostResult[] postResults = AcctSeed.BillingPostService.postBillings(billings);
    
    //Create Cash Receipt for Payment
    //   AcctSeed__Cash_Receipt__c[] CashRcpt = new List <AcctSeed__Cash_Receipt__c> ();
        AcctSeed__Cash_Receipt__c objCashReceipt = new AcctSeed__Cash_Receipt__c();
        objCashReceipt.AcctSeed__Amount__c = Oppty.Amount;
        objCashReceipt.AcctSeed__Account__c = Oppty.AccountId;
        objCashReceipt.AcctSeed__Payment_Reference__c = 'iDonate Pledge';
        objCashReceipt.AcctSeed__Receipt_Date__c = System.today();
         insert objCashReceipt;
     I have this Apex trigger but I keep getting an error       
            
        AcctSeed__Billing_Cash_Receipt__c     objBCR = new AcctSeed__Billing_Cash_Receipt__c();
        objBCR.AcctSeed__Billing__c = bill.id;
        objBCR.AcctSeed__Cash_Receipt__c = objCashReceipt.id;
        objBCR.AcctSeed__Applied_Amount__c = objCashReceipt.AcctSeed__Amount__c;
        insert objBCR;
I have written a test class for which it is showing 45% coverage, when i clicked on the code coverage to see what part of my code is not tested, the option is none and i cant see all tests option also i cannot see the blue and red coloured highlights in my test class? how can i see the coloured highlights and how can i get the all tests option?
THANKS!
I am not able to show the custom validation error message as a result of  callback method.

Controller.js
saveCase : function(component, event, helper){
       //existing validations...
       var validTab1 = helper.validateTab1(component); 
       var validTab2 = helper.validateTab2(component); 
       
        //New validaiotn      
        var isValidDate =           helper.validateExtDate(component);
        // Other business validations....
        helper.createCase(compoent);

}


Helper.js
 
validateExtDate:function(component)
{
    var caseRec = component.get("v.case");
    var action = component.get("c.getResponseDeadlineOnEdit");
    action.setParams({
                                "cs":caseRec
    });

    action.setCallback(this,function(response){
             this.processresults(response, component);
    });
    $A.enqueueAction(action);
},

processresults : function(response,component) {
    var extnsDate = component.find("respExtdate");
    var extnsDateVal = extnsDate.get("v.value");
    var extDate = new Date(extnsDateVal);

    var state = response.getState();
    if(state === "SUCCESS") {
         var deadlinedate= response.getReturnValue();      
         if(extDate <=  deadlineDate) {
                    extnsDate.set("v.errors", [{message: "Please select a different date” }]);
        }
}

The contoller.js is executing all the helper methods including the new asynch/callback method in helper.  But it is not stopping the flow if the custom validation occurs. i.e Due to asynch behaviour the flow is executing the existing createCase method, which save the case even if there is a validation. 
  • July 19, 2019
  • Like
  • 0
Our org has a trigger that will update contact fields to corresponding account fields when changed. We are getting a lot of CPU time limit exceeded emails for some reason.

Here is what we have for the trigger:
AccountAfterUpdate on Account (after update) {
    
    list<Account> accounts = new list<Account>();

    // Loop through Accounts to gather modified fields
    for (Account acct : Trigger.New) {
            
        Account oldAcct = Trigger.oldMap.get(acct.Id);

/*
i_Account_Type
i_PSA/CRM
i_RMM

i_ET_Customer
i_ET_Exp_Date
i_NA_Customer
i_NA_Exp_Date
i_NA_LastRun_Date
i_NA_Purch_Date
i_NA_Report_Count
i_PW_Customer
i_PW_Exp_Date
i_SA_Customer
i_SA_Exp_Date
i_SA_LastRun_Date
i_SA_Purch_Date
i_SA_Report_Count
i_TD_Customer
i_TD_Exp_Date
i_BDR_RunCount_1y__c
i_BDR_RunCount_30d__c
i_BDR_RunCount_90d__c
i_DetectorSDS_NumDeployed__c
i_DetectorSDS_Purch_Date__c
i_EA_RunCount_1y__c
i_EA_RunCount_30d__c
i_EA_RunCount_90d__c
i_HIPAA_RunCount_1y__c
i_HIPAA_RunCount_30d__c
i_HIPAA_RunCount_90d__c
i_NA_RunCount_1y__c
i_NA_RunCount_30d__c
i_NA_RunCount_90d__c
i_PCI_RunCount_1y__c
i_PCI_RunCount_30d__c
i_PCI_RunCount_90d__c
i_Reporter_Units__c
i_SA_RunCount_1y__c
i_SA_RunCount_30d__c
i_SA_RunCount_90d__c
i_SQL_RunCount_1y__c
i_SQL_RunCount_30d__c
i_SQL_RunCount_90d__c

i_Type_of_IT__c

i_ET_Price__c
i_TD_Price__c
i_SA_Price__c
i_PW_Price__c
i_NA_Price__c

i_EA_Customer__c
i_EA_Exp_Date__c
i_EA_LastRun_Date__c
i_EA_Purch_Date__c
i_EA_Report_Count__c
i_EA_Price__c

i_ND_Module_Count__c

i_CC_Exp_Date__c
i_ET_Purch_Date__c
i_Affiliations__c


i_SQL_Customer__c
i_SQL_Exp_Date__c
i_SQL_LastRun_Date__c
i_SQL_Price__c
i_SQL_Purch_Date__c
i_SQL_Report_Count__c

i__CNCT_Customer__c
i__CNCT_Purch_Date__c
i__CNCT_Exp_Date__c
i__CNCT_Price__c

i_HIPAA_Customer__c
i_HIPAA_Exp_Date__c
i_HIPAA_Price__c
i_HIPAA_Purch_Date__c

i_INSPECTOR_Customer__c
i_INSPECTOR_Units__c

Affiliation_ASCII__c
Affiliation_CharTec__c
Affiliation_CompTIA__c
Affiliation_HTG__c
Affiliation_RR__c

Business_Type__c, FMIT_ID__c, i_HIPAA_Report_Count__c, i_HIPAA_LastRun_Date__c,
i_NDS_HC_Customer__c, i_NDS_HC_Exp_Date__c, i_NDS_HC_Purch_Date__c, i_NDS_HC_Price__c, i_NDS_HC_Report_Count__c, i_NDS_HC_LastRun_Date__c

i_PCI_Customer__c, i_PCI_Exp_Date__c, i_PCI_LastRun_Date__c, i_PCI_Price__c, i_PCI_Purch_Date__c, i_PCI_Report_Count__c,
i_MSA_Customer__c, i_MSA_Exp_Date__c, i_MSA_LastRun_Date__c, i_MSA_Price__c, i_MSA_Purch_Date__c, i_MSA_Report_Count__c

i_DETECTOR_Customer__c, i_DETECTOR_Units__c, i_REPORTER_Customer__c, i_REPORTER_Units__c, Sales_Rep__c, i_OEM_Continuum__c

i_BDR_Customer_c__c, i_BDR_Exp_Date_c__c, i_BDR_LastRun_Date_c__c, i_BDR_Price_c__c, i_BDR_Purch_Date_c__c, i_BDR_Report_Count_c__c

i_DetectorSDS_Customer__c, i_DetectorSDS_Exp_Date__c, i_DetectorSDS_LastActivation_Date__c, i_DetectorSDS_NumDeployed__c, i_DetectorSDS_Price__c, i_DetectorSDS_Purch_Date__c

*/

        if (acct.i_Account_Type__c != oldAcct.i_Account_Type__c || acct.i_PSA_CRM__c != oldAcct.i_PSA_CRM__c ||
            acct.i_RMM__c != oldAcct.i_RMM__c || acct.i_ET_Customer__c != oldAcct.i_ET_Customer__c ||
            acct.i_ET_Exp_Date__c != oldAcct.i_ET_Exp_Date__c || acct.i_NA_Customer__c != oldAcct.i_NA_Customer__c || 
            acct.i_NA_Exp_Date__c != oldAcct.i_NA_Exp_Date__c || acct.i_NA_LastRun_Date__c != oldAcct.i_NA_LastRun_Date__c || 
            acct.i_NA_Purch_Date__c != oldAcct.i_NA_Purch_Date__c || acct.i_NA_Report_Count__c != oldAcct.i_NA_Report_Count__c || 
            acct.i_PW_Customer__c != oldAcct.i_PW_Customer__c || acct.i_PW_Exp_Date__c != oldAcct.i_PW_Exp_Date__c || 
            acct.i_SA_Customer__c != oldAcct.i_SA_Customer__c || acct.i_SA_Exp_Date__c != oldAcct.i_SA_Exp_Date__c || 
            acct.i_SA_LastRun_Date__c != oldAcct.i_SA_LastRun_Date__c || acct.i_SA_Purch_Date__c != oldAcct.i_SA_Purch_Date__c || 
            acct.i_SA_Report_Count__c != oldAcct.i_SA_Report_Count__c ||  
            acct.i_Type_of_IT__c != oldAcct.i_Type_of_IT__c || acct.i_ET_Price__c != oldAcct.i_ET_Price__c ||
            acct.i_SA_Price__c != oldAcct.i_SA_Price__c || 
            acct.i_PW_Price__c != oldAcct.i_PW_Price__c || acct.i_NA_Price__c != oldAcct.i_NA_Price__c || 
            acct.i_EA_Customer__c != oldAcct.i_EA_Customer__c || acct.i_EA_Exp_Date__c != oldAcct.i_EA_Exp_Date__c ||
            acct.i_EA_LastRun_Date__c != oldAcct.i_EA_LastRun_Date__c || acct.i_EA_Purch_Date__c != oldAcct.i_EA_Purch_Date__c ||
            acct.i_EA_Report_Count__c != oldAcct.i_EA_Report_Count__c || acct.i_EA_Price__c != oldAcct.i_EA_Price__c ||
            acct.i_ND_Module_Count__c != oldAcct.i_ND_Module_Count__c || acct.i_CC_Exp_Date__c != oldAcct.i_CC_Exp_Date__c ||
            acct.i_ET_Purch_Date__c != oldAcct.i_ET_Purch_Date__c || acct.i_Affiliations__c != oldAcct.i_Affiliations__c || 
            acct.i_Refresh__c != oldAcct.i_Refresh__c || 
            acct.i_SQL_Customer__c != oldAcct.i_SQL_Customer__c || acct.i_SQL_Exp_Date__c != oldAcct.i_SQL_Exp_Date__c ||
            acct.i_SQL_LastRun_Date__c != oldAcct.i_SQL_LastRun_Date__c || acct.i_SQL_Price__c != oldAcct.i_SQL_Price__c ||
            acct.i_SQL_Purch_Date__c != oldAcct.i_SQL_Purch_Date__c || acct.i_SQL_Report_Count__c != oldAcct.i_SQL_Report_Count__c ||
            acct.i_CNCT_Customer__c != oldAcct.i_CNCT_Customer__c || acct.i_CNCT_Purch_Date__c != oldAcct.i_CNCT_Purch_Date__c ||
            acct.i_CNCT_Exp_Date__c != oldAcct.i_CNCT_Exp_Date__c || acct.i_CNCT_Price__c != oldAcct.i_CNCT_Price__c ||
            acct.i_HIPAA_Customer__c != oldAcct.i_HIPAA_Customer__c || acct.i_HIPAA_Exp_Date__c != oldAcct.i_HIPAA_Exp_Date__c ||
            acct.i_HIPAA_Price__c != oldAcct.i_HIPAA_Price__c || acct.i_HIPAA_Purch_Date__c != oldAcct.i_HIPAA_Purch_Date__c ||
            acct.i_INSPECTOR_Customer__c != oldAcct.i_INSPECTOR_Customer__c || acct.i_INSPECTOR_Units__c != oldAcct.i_INSPECTOR_Units__c ||
            acct.Affiliation_ASCII__c != oldAcct.Affiliation_ASCII__c || acct.Affiliation_CharTec__c != oldAcct.Affiliation_CharTec__c ||
            acct.Affiliation_CompTIA__c != oldAcct.Affiliation_CompTIA__c || acct.Affiliation_HTG__c != oldAcct.Affiliation_HTG__c ||
            acct.Affiliation_RR__c != oldAcct.Affiliation_RR__c ||
            acct.Business_Type__c != oldAcct.Business_Type__c || acct.FMIT_ID__c != oldAcct.FMIT_ID__c || acct.i_HIPAA_Report_Count__c != oldAcct.i_HIPAA_Report_Count__c || 
            acct.i_HIPAA_LastRun_Date__c != oldAcct.i_HIPAA_LastRun_Date__c || 
            acct.i_PCI_Customer__c != oldAcct.i_PCI_Customer__c || acct.i_PCI_Exp_Date__c != oldAcct.i_PCI_Exp_Date__c || acct.i_PCI_LastRun_Date__c != oldAcct.i_PCI_LastRun_Date__c || 
            acct.i_PCI_Price__c != oldAcct.i_PCI_Price__c || acct.i_PCI_Purch_Date__c != oldAcct.i_PCI_Purch_Date__c || acct.i_PCI_Report_Count__c != oldAcct.i_PCI_Report_Count__c ||
            acct.i_DETECTOR_Customer__c != oldAcct.i_DETECTOR_Customer__c || acct.i_DETECTOR_Units__c != oldAcct.i_DETECTOR_Units__c || 
            acct.i_REPORTER_Customer__c != oldAcct.i_REPORTER_Customer__c || acct.i_REPORTER_Units__c != oldAcct.i_REPORTER_Units__c || acct.Sales_Rep__c != oldAcct.Sales_Rep__c ||
            acct.i_OEM_Continuum__c != oldAcct.i_OEM_Continuum__c ||
            acct.i_BDR_Customer_c__c != oldAcct.i_BDR_Customer_c__c || acct.i_BDR_Exp_Date_c__c != oldAcct.i_BDR_Exp_Date_c__c || 
            acct.i_BDR_LastRun_Date_c__c != oldAcct.i_BDR_LastRun_Date_c__c || acct.i_BDR_Price_c__c != oldAcct.i_BDR_Price_c__c || 
            acct.i_BDR_Purch_Date_c__c != oldAcct.i_BDR_Purch_Date_c__c || acct.i_BDR_Report_Count_c__c != oldAcct.i_BDR_Report_Count_c__c ||
            acct.i_DetectorSDS_Customer__c != oldAcct.i_DetectorSDS_Customer__c || 
            acct.i_DetectorSDS_Exp_Date__c != oldAcct.i_DetectorSDS_Exp_Date__c || 
            acct.i_DetectorSDS_LastActivation_Date__c != oldAcct.i_DetectorSDS_LastActivation_Date__c || 
            acct.i_DetectorSDS_NumDeployed__c != oldAcct.i_DetectorSDS_NumDeployed__c || 
            acct.i_DetectorSDS_Price__c != oldAcct.i_DetectorSDS_Price__c ||
            acct.i_DetectorSDS_Purch_Date__c != oldAcct.i_DetectorSDS_Purch_Date__c ||
            acct.i_CyberHawk_ABDS_Sites__c != oldacct.i_CyberHawk_ABDS_Sites__c ||
            acct.i_CyberHawk_BDS_Sites__c != oldacct.i_CyberHawk_BDS_Sites__c ||
            acct.i_BDR_RunCount_1y__c != oldacct.i_BDR_RunCount_1y__c ||
            acct.i_BDR_RunCount_30d__c != oldacct.i_BDR_RunCount_30d__c ||
            acct.i_BDR_RunCount_90d__c != oldacct.i_BDR_RunCount_90d__c ||
            acct.i_EA_RunCount_1y__c != oldacct.i_EA_RunCount_1y__c ||
            acct.i_EA_RunCount_30d__c != oldacct.i_EA_RunCount_30d__c ||
            acct.i_EA_RunCount_90d__c != oldacct.i_EA_RunCount_90d__c ||
            acct.i_HIPAA_RunCount_1y__c != oldacct.i_HIPAA_RunCount_1y__c ||
            acct.i_HIPAA_RunCount_30d__c != oldacct.i_HIPAA_RunCount_30d__c ||
            acct.i_HIPAA_RunCount_90d__c != oldacct.i_HIPAA_RunCount_90d__c  ||
            acct.i_NA_RunCount_1y__c != oldacct.i_NA_RunCount_1y__c ||
            acct.i_NA_RunCount_30d__c != oldacct.i_NA_RunCount_30d__c ||
            acct.i_NA_RunCount_90d__c != oldacct.i_NA_RunCount_90d__c ||
            acct.i_PCI_RunCount_1y__c != oldacct.i_PCI_RunCount_1y__c ||
            acct.i_PCI_RunCount_30d__c != oldacct.i_PCI_RunCount_30d__c ||
            acct.i_PCI_RunCount_90d__c != oldacct.i_PCI_RunCount_90d__c ||
            acct.i_SA_RunCount_1y__c != oldacct.i_SA_RunCount_1y__c ||
            acct.i_SA_RunCount_30d__c != oldacct.i_SA_RunCount_30d__c ||
            acct.i_SA_RunCount_90d__c != oldacct.i_SA_RunCount_90d__c ||
            acct.i_SQL_RunCount_1y__c != oldacct.i_SQL_RunCount_1y__c ||
            acct.i_SQL_RunCount_30d__c != oldacct.i_SQL_RunCount_30d__c ||
            acct.i_SQL_RunCount_90d__c != oldacct.i_SQL_RunCount_90d__c ||
            acct.i_Reporter_Purch_Date__c != oldacct.i_Reporter_Purch_Date__c ||
            acct.i_Reporter_Exp_Date__c != oldacct.i_Reporter_Exp_Date__c ||
            acct.i_AGP_GDPR_Units__c != oldacct.i_AGP_GDPR_Units__c ||
            acct.i_AGP_Program__c  != oldacct.i_AGP_Program__c ||
            acct.i_AGP_Purch_Date__c != oldacct.i_AGP_Purch_Date__c ||
            acct.i_AG_GDPR_Exp_Date__c != oldacct.i_AG_GDPR_Exp_Date__c ||
            acct.i_AG_GDPR_Price__c != oldacct.i_AG_GDPR_Price__c ||
            acct.i_AG_HIPAA_Customer__c != oldacct.i_AG_HIPAA_Customer__c ||
            acct.i_AG_HIPAA_Exp_Date__c != oldacct.i_AG_HIPAA_Exp_Date__c ||
            acct.i_AG_HIPAA_Price__c != oldacct.i_AG_HIPAA_Price__c ||
            acct.i_AG_HIPAA_Purch_Date__c != oldacct.i_AG_HIPAA_Purch_Date__c ||
            acct.i_AG_HIPAA_Units__c != oldacct.i_AG_HIPAA_Units__c ||
            acct.ob_Cyber_Hawk__c    != oldacct.ob_Cyber_Hawk__c  ||      
            acct.ob_Cyber_Hawk_Date__c    != oldacct.ob_Cyber_Hawk_Date__c   ||      
            acct.ob_Exchange__c    != oldacct.ob_Exchange__c      ||
            acct.ob_Exchange_Date__c    != oldacct.ob_Exchange_Date__c      ||
            acct.ob_GDPR__c    != oldacct.ob_GDPR__c      ||
            acct.ob_GDPR_Date__c    != oldacct.ob_GDPR_Date__c      ||
            acct.ob_HIPAA__c    != oldacct.ob_HIPAA__c      ||
            acct.ob_HIPAA_Date__c    != oldacct.ob_HIPAA_Date__c  ||       
            acct.ob_Inspector__c    != oldacct.ob_Inspector__c    ||
            acct.ob_Inspector_Date__c    != oldacct.ob_Inspector_Date__c ||
            acct.ob_NAM_SAM__c    != oldacct.ob_NAM_SAM__c ||       
            acct.ob_NAM_SAM_Date__c    != oldacct.ob_NAM_SAM_Date__c ||      
            acct.ob_PCI__c    != oldacct.ob_PCI__c ||       
            acct.ob_PCI_Date__c    != oldacct.ob_PCI_Date__c ||      
            acct.ob_Reporter__c    != oldacct.ob_Reporter__c ||      
            acct.ob_Reporter_Date__c    != oldacct.ob_Reporter_Date__c ||    
            acct.ob_SQL__c    != oldacct.ob_SQL__c ||
            acct.ob_SQL_Date__c    != oldacct.ob_SQL_Date__c  ||
            acct.Lead_Status__c != oldacct.Lead_Status__c   ||
            acct.Lead_Status_Reason__c != oldacct.Lead_Status_Reason__c ||
            acct.Already_Being_Worked__c != oldacct.Already_Being_Worked__c ||
            acct.i_DWID_Customer__c != oldacct.i_DWID_Customer__c ||
            acct.i_DWID_Exp_Date__c != oldacct.i_DWID_Exp_Date__c ||
            acct.i_DWID_Level__c != oldacct.i_DWID_Level__c ||
            acct.i_DWID_Price__c != oldacct.i_DWID_Price__c ||
            acct.i_DWID_Purch_Date__c != oldacct.i_DWID_Purch_Date__c ||
            acct.i_AG_CI_Customer__c != oldacct.i_AG_CI_Customer__c ||
            acct.i_AG_CI_Exp_Date__c != oldacct.i_AG_CI_Exp_Date__c ||
            acct.i_AG_CI_Price__c != oldacct.i_AG_CI_Price__c ||
            acct.i_AG_CI_Purch_Date__c != oldacct.i_AG_CI_Purch_Date__c ||
            acct.i_AG_CI_Units__c != oldacct.i_AG_CI_Units__c 
            ) {

                accounts.add(acct);
        }
    }

    ProactiveWatchHelper.UpdateContactDetails(accounts);

 
Hello Ohana,

If I understood correctly, if I pass 1000 records in the below batch, it will divide across 5 sub batch(200 each). The List<CSVGenerator.Values>  will hold value only for the final batch. What I am looking at is the List<CSVGenerator.Values>  should store the values of all the 5 sub batches which I will be passing to another method in my FINISH method. Need help here.
 
public class BatchToGenerateCSVForMarin implements Database.Batchable<sObject>, Database.Stateful {
    
    public List<CSVGenerator.Values> indiaGoogleValList = new List<CSVGenerator.Values>();
    public List<CSVGenerator.Values> indiaFacebookValList = new List<CSVGenerator.Values>();
    
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'SELECT ID,Email,Status,CreatedDate,Lead_GEO__c,GCLID__c,MKWID__c,MSCLICKID__c,FBCLID__c FROM Lead WHERE RecordType.Name=\'B2C\' AND Status!=\'Duplicate\'';
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext BC, List<Lead>scope){
        try{
            Set<Id> indiaLeadID = new Set<Id>();
            Set<Id> ROWLeadID = new Set<Id>();
            Set<Id> USLeadID = new Set<Id>();
            for(Lead l : scope){
                if(l.Lead_GEO__c!=null && l.Lead_GEO__c =='INDIA'){
                    indiaLeadID.add(l.Id);
                }
            }
            
            Map<String,Integer> googleIDIndiaMap = new Map<String,Integer>();
            Map<String,Integer> marinIDIndiaMap = new Map<String,Integer>();
            
            List<AggregateResult> leadMarketingIDAgg = [SELECT Count(ID)id, GCLID__c googleID, MKWID__c marinID, MSCLICKID__c bingID, FBCLID__c facebookID FROM Lead WHERE ID IN:indiaLeadID Group By GCLID__c,MKWID__c,MSCLICKID__c,FBCLID__c];
            
            for(AggregateResult agg : leadMarketingIDAgg){
                if((String)agg.get('googleID')!=null){
                    googleIDIndiaMap.put((String)agg.get('googleID'), (Integer)agg.get('id'));
                }
                if((String)agg.get('marinID')!=null){
                    marinIDIndiaMap.put((String)agg.get('marinID'), (Integer)agg.get('id'));
                }
            }
            
            for(String s : googleIDIndiaMap.keySet()){
                CSVGenerator.Values val = new CSVGenerator.Values();
                val.recordDate = String.valueof(System.today());
                val.conversionType = 'Lead';
                val.conversions = string.valueof(googleIDIndiaMap.get(s));
                val.revenue = '0';
                val.currencyCode = '';
                val.comments = s;
                indiaGoogleValList.add(val);
            }
            
            for(String s : marinIDIndiaMap.keySet()){
                CSVGenerator.Values val = new CSVGenerator.Values();
                val.recordDate = String.valueof(System.today());
                val.conversionType = 'Lead';
                val.conversions = string.valueof(marinIDIndiaMap.get(s));
                val.revenue = '0';
                val.currencyCode = '';
                val.comments = s;
                indiaMarinValList.add(val);
            }
    }
    
    public void finish(Database.BatchableContext BC){
        if(indiaGoogleValList.size() > 0){
            CSVGenerator.generateCsv('Marin', indiaGoogleValList, 'Google', 'INDIA');
        }       
        if(indiaMarinValList.size() > 0){
            CSVGenerator.generateCsv('Marin', indiaMarinValList, 'Marin', 'INDIA');
        }
    } 
}