You need to sign in to do that
Don't have an account?

Trigger that creates contacts when an account is created
I'm new to apex and currently learning variables and trigger. I'm creating simple scenarios and attempting to write triggers for those scenarios. Below are the 2 scenarios I need help with;
Write a trigger that creates a contact when an account is created and should be associated with the account.
Write a trigger that creates two identical Contacts whenever an account is created and should be associated with the account.
Here's the trigger I wrote for the first scenario and I get an error when I try to create a new account.
How do I go about the second trigger?
trigger AccountCreate on Account (after insert) {
for (Account acc : Trigger.new) {
Contact C = new Contact();
C.LastName = 'Grace';
C.AccountId = acc.id;
C.Email = 'testme@hotmail.com';
insert acc;
}
}
Write a trigger that creates a contact when an account is created and should be associated with the account.
Write a trigger that creates two identical Contacts whenever an account is created and should be associated with the account.
Here's the trigger I wrote for the first scenario and I get an error when I try to create a new account.
How do I go about the second trigger?
trigger AccountCreate on Account (after insert) {
for (Account acc : Trigger.new) {
Contact C = new Contact();
C.LastName = 'Grace';
C.AccountId = acc.id;
C.Email = 'testme@hotmail.com';
insert acc;
}
}
Always remember that you will not use DML statements inside trigger, especially for the Object you are insert. Remember following things:
- No Insert in before / after insert.
- No Update in Before insert.
- No Update in before / after Delete.
- No insert in befote / after update
- No update in before update.
Here you will need to Insert the contact and hence you will have to use as per your code. For the code where you need to make two contact for each account use following code. Hope the solution helped you in solving your problem. If it did do give a like :)All Answers
Always remember that you will not use DML statements inside trigger, especially for the Object you are insert. Remember following things:
- No Insert in before / after insert.
- No Update in Before insert.
- No Update in before / after Delete.
- No insert in befote / after update
- No update in before update.
Here you will need to Insert the contact and hence you will have to use as per your code. For the code where you need to make two contact for each account use following code. Hope the solution helped you in solving your problem. If it did do give a like :)