function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nabeel Munir 9Nabeel Munir 9 

Update a custom field in account after insert

Hello,
I am a newbie in salesforce and practicing apex triggers using the following scenerio.
Pre-Reqs:
Create a field on Account called “Only_Default_Contact”, checkbox, default off
Assignment:
When a new Account is created, create a new Contact that has the following data points:
First Name = “Info”
Last Name = “Default”
Email = “info@websitedomain.tld”
Only_Default_Contact = TRUE
When the Account has more than 1 Contact, update Only_Default_Contact to FALSE.

So far I have only been able to create contacts related to account after insert. But, since I know that after insert, Account becomes read only. I needed a way to update the Only_Default_Contact__c field. 
Below is what I have tried but it does not seem to work. 

trigger createAccount on Account (after insert,before update)
{
   List<Contact> lst = new List<Contact>();
    Contact con = new Contact();
    if(trigger.isAfter && trigger.isInsert)
  {
   for(Account acc:trigger.new)
   {
     con.AccountId = acc.Id;
     con.FirstName = 'Info';
     con.LastName = 'Default';
     con.Email = 'info@websitedomain.tld';
     
     lst.add(con);    
   }
  }
   if(!lst.isEmpty())
   {
      insert lst;
   
   }
   
   
   if(trigger.isBefore && trigger.isUpdate)
   {
   List<Account> ls = [Select Only_Default_Contact__c from Account];
   for(Account a: trigger.new)
     {
      if(lst.size()==1)
        {
        a.Only_Default_Contact__c = TRUE;
        update a;
        }
        else
        {
          a.Only_Default_Contact__c = FALSE;
          update a;
        }
   }
   }
}
Best Answer chosen by Nabeel Munir 9
Khan AnasKhan Anas (Salesforce Developers) 
Hi Nabeel,

Greetings to you!

You need to create 2 triggers, one on Account and second one Contact object. AccountTrigger will create a new contact on account insertion. ContactTrigger will update the checkbox on Account. 

Please try below code:

AccountTrigger:
trigger AccountTrigger on Account (after insert) {
    if(trigger.isafter && trigger.isinsert) {
		Handler_AccConTrigger.newContactCreated(Trigger.new);
    }
}

ContactTrigger:
trigger ContactTrigger on Contact (after insert) {
    if(trigger.isafter && trigger.isinsert) {
		Handler_AccConTrigger.updateCheckboxOnAccount(Trigger.new);
    }
}

Handler Class:
public class Handler_AccConTrigger {
	// Method to handle the contact inserts.
	public static void newContactCreated(List<Account> accList){
		List<Contact> conList = new List<Contact>();
		for(Account acc : accList) {
			  Contact con = new Contact(AccountId = acc.Id);
			  List<String> nameStr = acc.Name.split(' ');
			  if(nameStr.size()>0)
				 con.LastName = nameStr[0];
			  if(nameStr.size()>1)
				  con.FirstName = nameStr[1];
				  
			con.Email = 'info@websitedomain.tld';
			con.Only_Default_Contact__c = TRUE;
			conList.add(con);
		}
		INSERT conList;		
	}
	public static void updateCheckboxOnAccount(List<Contact> contactList){
		Set<Id> accountIds = new Set<Id>();
		for(Contact con : contactList) {
			 accountIds.add(con.AccountId);
		}
		
		List<Account> updatedAccounts = new List<Account>();
		for(AggregateResult ar : [SELECT count(id) , AccountId FROM Contact WHERE AccountId IN :accountIds GROUP BY AccountId having count(id)  >1 ]){
			updatedAccounts.add(new Account(Id = (Id)ar.get('AccountId'), Only_Default_Contact__c=false));    
		}
		
		if(!updatedAccounts.isEmpty())
			UPDATE updatedAccounts;
	}
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Nabeel,

Greetings to you!

You need to create 2 triggers, one on Account and second one Contact object. AccountTrigger will create a new contact on account insertion. ContactTrigger will update the checkbox on Account. 

Please try below code:

AccountTrigger:
trigger AccountTrigger on Account (after insert) {
    if(trigger.isafter && trigger.isinsert) {
		Handler_AccConTrigger.newContactCreated(Trigger.new);
    }
}

ContactTrigger:
trigger ContactTrigger on Contact (after insert) {
    if(trigger.isafter && trigger.isinsert) {
		Handler_AccConTrigger.updateCheckboxOnAccount(Trigger.new);
    }
}

Handler Class:
public class Handler_AccConTrigger {
	// Method to handle the contact inserts.
	public static void newContactCreated(List<Account> accList){
		List<Contact> conList = new List<Contact>();
		for(Account acc : accList) {
			  Contact con = new Contact(AccountId = acc.Id);
			  List<String> nameStr = acc.Name.split(' ');
			  if(nameStr.size()>0)
				 con.LastName = nameStr[0];
			  if(nameStr.size()>1)
				  con.FirstName = nameStr[1];
				  
			con.Email = 'info@websitedomain.tld';
			con.Only_Default_Contact__c = TRUE;
			conList.add(con);
		}
		INSERT conList;		
	}
	public static void updateCheckboxOnAccount(List<Contact> contactList){
		Set<Id> accountIds = new Set<Id>();
		for(Contact con : contactList) {
			 accountIds.add(con.AccountId);
		}
		
		List<Account> updatedAccounts = new List<Account>();
		for(AggregateResult ar : [SELECT count(id) , AccountId FROM Contact WHERE AccountId IN :accountIds GROUP BY AccountId having count(id)  >1 ]){
			updatedAccounts.add(new Account(Id = (Id)ar.get('AccountId'), Only_Default_Contact__c=false));    
		}
		
		if(!updatedAccounts.isEmpty())
			UPDATE updatedAccounts;
	}
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer
Nabeel Munir 9Nabeel Munir 9
Thank you khan Anas, It helped.
Deepali KulshresthaDeepali Kulshrestha
Hi Nabeel,
Please follow the given below code with the help of these you can solve your problem, it may be helpful to you.

Apex Trigger :
 
trigger TriggerOnAccountYA on Account(after insert, after update) {
    if(Trigger.isAfter && Trigger.isInsert){
        TriggerOnAccountYAHandler.createContact(trigger.old, trigger.new);
    }

    if(Trigger.isAfter && Trigger.isUpdate){
        TriggerOnAccountYAHandler.createContact(trigger.old,trigger.new);
    }
}

Apex Trigger Controller :

public class TriggerOnAccountYAHandler {
    public static void createContact(List<Account> accListOld, List<Account>accList){
        try{
            System.debug('Inside TriggerOnAccountYAHandler');
            List<Account>accConList = new List<Account>();
            Set<Id> accSet=new Set<Id>();
                if(accListOld == null){
                    if(accList.size()>0) {
                        List<Contact> conList = new List<Contact>();
                        List<Account>NewAccList = new List<Account>();
                        for (Account acc : accList) {
                            Account accInst = new Account();
                            accInst.Id = acc.Id;
                            accInst.Name = acc.Name;
                            accInst.Only_Default_Contact__c = TRUE;
                            NewAccList.add(accInst);
                            accSet.add(acc.Id);
                            Contact con = new Contact();
                            con.AccountId = acc.Id;
                            con.FirstName = 'Info';
                            con.LastName = 'Default';
                            con.UserName__c = 'test@123';
                            con.Password__c = '1234567';
                            con.Email = 'info@websitedomain.tld';
                            conList.add(con);
                        }
                        System.debug('accList-->'+accList);
                        if (conList.size() > 0) {
                            insert conList;
                        }
                        if (NewAccList.size() > 0) {
                            update NewAccList;
                        }
                        accConList = [SELECT Id,(SELECT Id FROM Contacts) FROM Account WHERE Id IN : accSet LIMIT 1000];
                        System.debug('accConList>>>>'+accConList);
                        for(Account accIn : accConList){
                            if(accIn.Contacts.size() > 1){

                                accIn.Only_Default_Contact__c = False;
                            }
                        }
                        if (accConList.size() > 0) {
                            update accConList;
                        }
                    }
                }
            else {
                if(accList.size()>0) {
                    List<Account>NewAccList = new List<Account>();
                    for (Account acc : accList) {
                        accSet.add(acc.Id);
                    }
                    accConList = [SELECT Id,Name,Only_Default_Contact__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN : accSet LIMIT 1000];
                    System.debug('accConList>>>'+accConList);

                    for (Account accIn : accConList) {
                        System.debug('accIn.Contacts.size()>>>'+accIn.Contacts.size());
                        if (accIn.Contacts.size() > 1) {

                            Account accInst = new Account();
                            accInst.Id = accIn.Id;
                            accInst.Name = accIn.Name;
                            accInst.Only_Default_Contact__c = False;
                            if(accIn.Only_Default_Contact__c == False){

                            }else{
                                NewAccList.add(accInst);
                            }
                        }
                        if (accIn.Contacts.size() ==1) {
                            Account accInst = new Account();
                            accInst.Id = accIn.Id;
                            accInst.Name = accIn.Name;
                            accInst.Only_Default_Contact__c = TRUE;
                            if(accIn.Only_Default_Contact__c == TRUE){
                            }else{
                                NewAccList.add(accInst);
                            }
                        }
                    }
                    if (NewAccList.size() > 0) {
                        update NewAccList;
                    }
                }
            }
        }catch (Exception ex){
            system.debug('Exception ae: '+ex.getMessage()+' '+ex.getLineNumber());
        }
    }
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
Sanjana_singh12Sanjana_singh12
How to create testclass for the above apex class