When a new Account is created, create a new Contact record and associate it with the Account
Creating related records is a common requirement in Salesforce development. In this blog, we will discuss how to automatically create a new Contact record and associate it with the Account when a new Account is created. We will use Apex trigger to achieve this.
Before we proceed, let's understand what triggers are in Salesforce. Triggers are code blocks that are executed before or after a record is inserted, updated, or deleted. Triggers allow you to perform custom actions on records before or after they are saved to the database.
To create a trigger that automatically creates a new Contact record and associates it with the Account, follow these steps:
Step 1: Create a new Apex trigger
To create a new Apex trigger, go to Setup > Object Manager and select the Account object. Click on the "New" button under "Triggers" to create a new trigger.
Step 2: Define the trigger properties
Enter a name for your trigger and select "After Insert" as the "Trigger Type". Under "Apex Class", select "Apex Trigger" and click "Save".
Step 3: Write the Apex code
In the Apex Trigger code editor, write the following code:
This code creates a new Contact record for each new Account record that is created. It sets the First Name and Last Name of the Contact record to "New Contact" and sets the AccountId field to the Id of the new Account record. Finally, it adds the Contact records to a list and inserts them into the database.
Step 4: Save and activate the trigger
Click "Save" to save your trigger. Now, when a new Account record is created, a new Contact record will automatically be created and associated with the Account.
In conclusion, creating related records is a common requirement in Salesforce development, and triggers can be used to achieve this. In this blog, we discussed how to automatically create a new Contact record and associate it with the Account when a new Account is created.
0 Comments