0

I am working on a task. To understand my issue let me describe what I am doing.


Object: staging__c

Fields:

Individual_or_Organization__c (Text)

Orgganization_Name__c

First_Name__c

Last_Name__c

Postal_Code__c

Date_Recieved__c (Date)

Amount__c (Currency)

Error_Message__c (Long Text)

Description__c

Requirement:

Case1. If Individual_or_Organization__c==I ,

Search for existing contact with matching FistName , LastName and Postal Code. If contact not found then create new contact.

If staging record contains value in Orgganization_Name__c and Postal_Code__c Fields then search for account with matching name and postal code. If account found then link contact record with this account.

Create new opportunity record for that contact

Case2. If Individual_or_Organization__c==O

Search for existing Account with matching Orgganization_Name__c and Postal Code. If Account not found then create new account.

If staging record contains value in Last_Name__c and Postal_Code__c Fields then search for contact with matching firstname,lastname and postal code. If contact found then link contact record with the account.

Create Opportunity record for account

Field Mapping for Opportunity:

OpportunityName = Account Name or Contact Name+CloseDate

CloseDate = Date_Recieved__c

Amount = Amount__C

Description=Description__c


As you saw the requirement I am working on "condition 1" I wrote a batch class for same but still it raising few errors please have a look at my code

global class BatchAssignment implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){     
        return Database.getQueryLocator([SELECT Id, Individual_or_Organization__c,Orgganization_Name__c,First_Name__c,Last_Name__c,Postal_Code__c,Date_Recieved__c,Amount__c,Error_Message__c,Description__c 
                                         FROM staging__c]);
    }    
    
    global void execute(Database.BatchableContext BC, List<staging__c> scope){
        List<Opportunity> newOpptyList = new List<Opportunity>();
        if(scope != null && scope.Individual_or_Organization__c == 'I') {
            Account objAccount = searchAccount(scope);
            if(objAccount != null) {
                List<Contact> linkContactList = searchContact(objAccount, scope);
                try{
                    if(linkContactList != null && !linkContactList.isEmpty()) {
                        upsert linkContactList;
                        
                        //Create new opportunity;
                        for(Contact objCon : linkContactList) {
                            newOpptyList.add(new Opportunity(Name = objCon.FullName,
                                                             StageName = 'Prospecting',
                                                             AccountId = objAccount.Id,
                                                             ContactId = objCon.Id
                                                            ));                         //Add other required fields if needed.
                            
                        }
                        
                        if(newOpptyList != null && !newOpptyList.isEmpty()) {
                            insert newOpptyList;
                        }
                    }
                }catch(Exception ex) {
                    system.debug('---Exception--' + ex);
                }
                
            }
        }
    }
    
    private Account searchAccount(staging__c scope) {
        if(scope.Orgganization_Name__c != null && scope.Postal_Code__c != null) {
            return [SELECT Id, Name FROM Account WHERE Name = :scope.Orgganization_Name__c AND BillingPostalCode = :scope.Postal_Code__c];
            //Assuming here, there will be only one account with these combination in your system
        }
    }
    
    
    private List<Contact> searchContact(Account objAccount, staging__c scope) {
        List<Contact> linkContactList = new List<Contact>();
        if(scope.First_Name__c != null && scope.Last_Name__c != null && scope.Postal_Code__c != null) {
            List<Contact> existingContactList = [SELECT Id, FirstName, LastName, MailingPostalCode FROM Contact 
                                                 WHERE FirstName = :scope.First_Name__c AND LastName = :scope.Last_Name__c AND MailingPostalCode = :scope.Postal_Code__c];
            //For existing contacts
            if(existingContactList != null) {
                for(Contact objCon : existingContactList) {
                    objCon.AccountId = objAccount.Id;
                    linkContactList.add(objCon);
                }
            } else {
                //create new contact
                linkContactList.add(new Contact(FirstName = scope.First_Name__c, 
                                                LastName = scope.Last_Name__c,
                                                MailingPostalCode = scope.Postal_Code__c
                                                AccountId = objAccount.Id));
            }
            
        }
        return linkContactList;
    }
    
    global void finish(Database.BatchableContext BC){        
    }

These are the errors I am unable to fix enter image description here

2 Answers 2

1

There were many errors in the code such that you are not looping the scope in the execute method, there were some issues regarding the open and close braces { and } and also ,. I have updated the code now i don't see any errors.

global class BatchAssignment implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){     
        return Database.getQueryLocator([SELECT Id, Individual_or_organization__c ,Orgganization_Name__c,First_Name__c,Last_Name__c,Postal_Code__c,Date_Recieved__c,Amount__c,Error_Message__c,Description__c 
                                         FROM staging__c]);
    }    
    
  global void execute(Database.BatchableContext BC, List<staging__c> scope){
        List<Opportunity> newOpptyList = new List<Opportunity>();
      for(staging__c sc:scope){
        if(sc != null && sc.Individual_or_organization__c  == 'I') {
            Account objAccount = searchAccount(sc);
            if(objAccount != null) {
                List<Contact> linkContactList = searchContact(objAccount, sc);
                system.debug('contact'+linkContactList);
                try{
                    if(linkContactList != null && !linkContactList.isEmpty()) {
                        upsert linkContactList;
                        
                        //Create new opportunity;
                        for(Contact objCon : linkContactList) {
                            newOpptyList.add(new Opportunity(Name = objCon.LastName,
                                                             StageName = 'Prospecting',
                                                             AccountId = objAccount.Id,
                                                             ContactId = objCon.Id,
                                                             CLOSEDATE=Date.today()
                                                            ));                         //Add other required fields if needed.
                            
                        }
                        
                        if(newOpptyList != null && !newOpptyList.isEmpty()) {
                            insert newOpptyList;
                        }
                    }
                }catch(Exception ex) {
                    system.debug('---Exception--' + ex);
                }
                
            }
        }
      }
    }
    
    private Account searchAccount(staging__c scope) {
        Account acc= new Account();
        if(scope.Orgganization_Name__c != null && scope.Postal_Code__c != null) {
            acc= [SELECT Id, Name FROM Account WHERE Name = :scope.Orgganization_Name__c AND BillingPostalCode = :scope.Postal_Code__c];
            //Assuming here, there will be only one account with these combination in your system
        }
        return acc;
    }
    
    
    private List<Contact> searchContact(Account objAccount, staging__c scope) {
        List<Contact> linkContactList = new List<Contact>();
        if(scope.First_Name__c != null && scope.Last_Name__c != null && scope.Postal_Code__c != null) {
            List<Contact> existingContactList = [SELECT Id, FirstName, LastName, MailingPostalCode FROM Contact 
                                                 WHERE FirstName = :scope.First_Name__c AND LastName = :scope.Last_Name__c AND MailingPostalCode = :scope.Postal_Code__c];
            //For existing contacts
            system.debug('existing contact'+existingContactList);
            if(existingContactList.size()>0 ) {
                for(Contact objCon : existingContactList) {
                    objCon.AccountId = objAccount.Id;
                    linkContactList.add(objCon);
                }
            } else {
                //create new contact
                system.debug('into else');
                linkContactList.add(new Contact(FirstName = scope.First_Name__c, 
                                                LastName = scope.Last_Name__c,
                                                MailingPostalCode = scope.Postal_Code__c,
                                                AccountId = objAccount.Id));
                system.debug('linked contact2'+linkContactList);
            }
            
        }
        return linkContactList;
    }
    
    global void finish(Database.BatchableContext BC){        
    }
}

Please find the below articles for best practices of batch apex and implementation as well.

Batch apex Article

3
  • It worked! Thank you so much I appreciate your help, I'll learn more from this documentation link you provide :) Commented Sep 10, 2021 at 8:59
  • hi, I notice one thing your solution is using soql inside for loop. Can't we exclude soql from the loop? Because I heard It's a bad practice :/ Commented Sep 14, 2021 at 7:27
  • 1
    Yes we can do it using aggregate updates by using set and Map Commented Sep 14, 2021 at 7:59
1

There are few compilation issue I see right from your code above.

  1. I see no closing curly braces at the end of the file.
  2. In Method searchAccount and searchContact params are list but your are expecting Single object while declaring the method.
  3. Method searchAccount does not have any return statement in else as the first return statement is inside if block.
  4. In method searchContact while adding it to linkContactList you missed a comma , after this scope.Postal_Code__c

I may have not identified more minutely, but These all are compilation issues which can be fixed from your end.

You must log in to answer this question.

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