forked from SalesforceSFDC/Apex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddRelatedRecordOnAccount.tgr
28 lines (24 loc) · 1.05 KB
/
AddRelatedRecordOnAccount.tgr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
trigger AddRelatedRecord on Account(after insert, after update) {
List<Opportunity> oppList = new List<Opportunity>();
// Get the related opportunities for the accounts
Map<Id, Account> acctWithOpps = 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 doesnt 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 doesnt, 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;
}
}