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
Mayur ShindeMayur Shinde 

Hello Team, I Want Write Trigger Could you pls Help Me how to write this Use Case Pls i am begginer..

Practice Use Case:

1.create a checkbox 'create contact' on Account.
2.create a trigger which handles events like account insert, update, delete.
3.Trigger will be responsible for creating contact with defined set of fields. It will be responsible to keep key information of contact updated from Account. Hence Account will still be treated as master for key information.  
Best Answer chosen by Mayur Shinde
Dev_AryaDev_Arya
Hello Mayur,
Did you mean, when user selects create Account checkbox and save the record, a trigger should and a related contact record should get created?
Do you really want this for account update and delete? Because this will fire the trigger every time the account is updated and does not make a use case to create a contact on Account delete.

but anyways, here it is :
trigger InsertContactOnAccountUpsert on Account (after insert, after update) {
	if(Trigger.isInsert)
    {
        List<Contact> ct = new List <Contact>();
        for (Account acc: Trigger.New)
        {
            //  Insert a contact on account insert with mapping
			// You can add the logic here to check if acount create contact is true or not
                 ct.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Last Name',
                         Email = 'Account@email.com',
                         AccountId = acc.id,
                         Fax=acc.Fax,
                         MailingStreet=acc.BillingStreet,
                         MailingCity=acc.BillingCity,
                         MailingState=acc.BillingState,
                         MailingPostalCode=acc.BillingPostalCode,
                         MailingCountry=acc.BillingCountry,
                         Phone=acc.Phone
                         )
                     );   
            
        }
        if(!ct.isEmpty())
            insert ct; 
    }
}

Hope this helps.

Cheers.​ 

All Answers

Mayur ShindeMayur Shinde
Hello team pls suggest me it's very helpful me..
Dev_AryaDev_Arya
Hello Mayur,
Did you mean, when user selects create Account checkbox and save the record, a trigger should and a related contact record should get created?
Do you really want this for account update and delete? Because this will fire the trigger every time the account is updated and does not make a use case to create a contact on Account delete.

but anyways, here it is :
trigger InsertContactOnAccountUpsert on Account (after insert, after update) {
	if(Trigger.isInsert)
    {
        List<Contact> ct = new List <Contact>();
        for (Account acc: Trigger.New)
        {
            //  Insert a contact on account insert with mapping
			// You can add the logic here to check if acount create contact is true or not
                 ct.add (new Contact(
                         FirstName = 'Account',
                         LastName = 'Last Name',
                         Email = 'Account@email.com',
                         AccountId = acc.id,
                         Fax=acc.Fax,
                         MailingStreet=acc.BillingStreet,
                         MailingCity=acc.BillingCity,
                         MailingState=acc.BillingState,
                         MailingPostalCode=acc.BillingPostalCode,
                         MailingCountry=acc.BillingCountry,
                         Phone=acc.Phone
                         )
                     );   
            
        }
        if(!ct.isEmpty())
            insert ct; 
    }
}

Hope this helps.

Cheers.​ 
This was selected as the best answer
Dev_AryaDev_Arya
Hi Mayur,
I would also prefer to use process builder instead of jumping directly to triggers. As best practice, one should try to achieve maximum with out of the box Point and click functionality from SF.

Cheers.
Mayur ShindeMayur Shinde

hi dev_arya...
Use case: i have to create a checkbox on Account object.
When someone clicks that checkbox as true corresponding Contact should be created.
Now once someone has marked it as true no one can change it again.
1. Any time someone changes details on Account record corresponding contact information should be updated/
2. If Account is deleted corresponding contact should be deleted
3. If Account is undeleted corresponding contact should be undeleted

colud you pls how to write this hanlder class and trigger Test class pls help its very urgent.........

+++++++++++++++++++Handler Class++++++++++++++++++++
public class contactRecordCreationHandlerClass{
    
    List<Contact> listContact =new List<Contact>();
    Map<Id,Account> accMap = new Map<Id,Account>(); 
    set<Id> List_Accounts = new set<Id>(); 
    // list<Contact> List_Cont= new list<Contact>();
    
    /*********************Insert Contact**************************/
    
    public void contactRecordCreationTriggerOperation(List<Account> AccountList)
    {
        try{
            if(AccountList!= null && !AccountList.isEmpty())
            {
                for(Account acc : AccountList) 
                {          
                    if(acc.Create_Contact__c == true)
                    {
                        
                        Contact con = new Contact();
                        
                        con.LastName =acc.First_Name__c;
                        con.AccountId=acc.id;
                        con.Email=acc.Email_Primary__c;
                        con.advpm__Other_Email__c=acc.Email_Other__c;               
                        con.Fax=acc.Fax;
                        con.MailingStreet=acc.BillingStreet;
                        con.MailingCity=acc.BillingCity;
                        con.MailingState=acc.BillingState;
                        con.MailingPostalCode=acc.BillingPostalCode;
                        con.MailingCountry=acc.BillingCountry;
                        con.Phone=acc.Phone;
                        con.Create_Contact_on_Account__c=True;
                        listContact.add(con);   
                    }                                                            
                    
                }  
                if(listContact !=null && !listContact.isEmpty())    
                {           
                    insert listContact ; 
                } 
                
            }
        }
        catch (Exception e)
        {
            system.debug('Exception error is'+e);
        }     
    }
    
    
    
    /***************************Update Record***************************/
    
    public void contactRecordupdateTriggerOperation(List<Account> accList, Map<Id,Account> accMap)
    {
        try{
            for(Contact conObj : [Select Id,accountId,Email,Fax,advpm__Other_Email__c,MailingStreet,MailingCity,MailingState,MailingPostalCode,MailingCountry,Create_Contact_on_Account__c from Contact where accountId IN : accMap.keySet()] )
            {
                if(conObj.Create_Contact_on_Account__c==True)
                {
                    if(accMap.containsKey(conObj.accountId))
                    {
                        Account accObj = accMap.get(conObj.accountId);
                        conObj.Email=accObj.Email_Primary__c;
                        conObj.advpm__Other_Email__c=accObj.Email_Other__c;               
                        conObj.Fax=accObj.Fax;
                        conObj.MailingStreet = accObj.BillingStreet;
                        conObj.MailingCity = accObj.BillingCity;
                        conObj.MailingState = accObj.BillingState;
                        conObj.MailingPostalCode = accObj.BillingPostalCode;
                        conObj.MailingCountry = accObj.BillingCountry;
                        
                        listContact .add(conObj);                                        
                    }
                }
            }
            
            if(listContact !=null && !listContact .isEmpty())
            { 
                update listContact ;                                               
            }
            
        }
        
        catch (Exception e)
        {
            system.debug('Exception error is'+e);
        }  
        
    }
    
    /***************************Undelete Record*******************************/
    
    public void contactRecordundeleteTriggerOperation(list<Account> List_Accounts)
    {
        
        if(List_Accounts!=null && List_Accounts.size()>0)
        {
            
            List_Accounts=[Select id,(Select id,Create_Contact_on_Account__c from contacts where Create_Contact_on_Account__c=TRUE) From Account];
            undelete List_Accounts;  
        }
    }
}


++++++++++++++++++++++++++++++trigger++++++++++++++++++++++++++++++++++++
trigger CreateAccountContact on Account (after insert, after update, after Undelete){
    
    //Trigger inactive Setting    
    Account__c TriggerSetting=Account__c.getInstance();
    
    if(!TriggerSetting.Create_Contact__c)
    {
        ContactRecordCreationHandlerClass contactrecord = new ContactRecordCreationHandlerClass();
        if(Trigger.isinsert  && Trigger.isafter )
        {
            contactrecord.contactRecordCreationTriggerOperation(Trigger.new);   
        }
        if( Trigger.isupdate && Trigger.isafter)
        {
            contactrecord.contactRecordupdateTriggerOperation(Trigger.old,Trigger.NewMap);   
        }
        
        if(Trigger.isUndelete && Trigger.isafter)
        {
            contactrecord.contactRecordundeleteTriggerOperation(Trigger.New);
        }
    }
}

pls help to test class for best practice.............
Dev_AryaDev_Arya
Hi Mayur,

I didn't get time to test your code but had a quick look. My observations:
  1. As far as I know, in your trigger, for after Update event(line 15), u have used Trigger.NewMap: For Update events NewMap does not work as there are no new records, U should use Trigger.OldMap to get the Ids of updates Accounts and also update your corresponding helper class function.
  2. in line 20, after Undelete, also Trigger.New is not allowed (but I am not sure, nvr tested it). You could read more about it in the trigger context variable considerations:
If you still have issues with the code, let me know but you should go through the link I provided above (its quite useful).

Cheers,
Dev