You need to sign in to do that
Don't have an account?
ifthikar Ahmed 1
help me complete this code
Hi I am trying to create a contact related record when a new account is created
trigger Createcontact on Account (before insert) {
List<Contact> contactList=new List<Contact>();
for (Account a : Trigger.new) {
Contact c=new Contact();
c.firstName=a.Name;
c.lastName=a.Name;
contactList.add(c);
// Iterate over each sObject
}
insert contactList;
}
the above trigger creates a new contact where in i want the contact to be related to the respective account
trigger Createcontact on Account (before insert) {
List<Contact> contactList=new List<Contact>();
for (Account a : Trigger.new) {
Contact c=new Contact();
c.firstName=a.Name;
c.lastName=a.Name;
contactList.add(c);
// Iterate over each sObject
}
insert contactList;
}
the above trigger creates a new contact where in i want the contact to be related to the respective account
It should be after insert not before insert. Thanks,
Nitish
All Answers
It should be after insert not before insert. Thanks,
Nitish
.can you pls clarify me why after insert ??
After Insert because you have to create a related contact for the account created. so for that you need ID of the created account so that you can build the relationship between contact and account. See line NO 7 where i have written c.accountId = a.Id;
In before insert event you cannot use Id becuase the time it will run it wont have id genrated and record saved in database. so you cannot use id to create another related record.
trigger AddRelatedRecord on Account(after insert, after update) {
List<Opportunity> oppList = new List<Opportunity>();
// Get the related opportunities for the accounts in this trigger
Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
[SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
// Add an opportunity for each account if it doesn't already have one.
// Iterate through each account.
for(Account a : Trigger.New) {
System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
// Check if the account already has a related opportunity.
if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
// If it doesn't, add a default opportunity
oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=a.Id));
}
}
if (oppList.size() > 0) {
insert oppList;
}
}
When you are trying to add new record its in before insert and by that time account record has not been saved in Database so Id is not yet genrated and you are trying to reffer that id in your opportunity record.
Change your trigger from before insert to after insert.
Thanks,
Nitish