You need to sign in to do that
Don't have an account?
Ranjith Mergu
Trigger for roll up summary fields
Hii All
I have 2 objects..1---Account--standard and 2---Transaction---custom object. In the transaction one field is there i.e., Transaction type. So my question is i want to update a field on account object record based on Transaction Type. How can i achieve this using Triggers(Like Roll up summary fields).
I have 2 objects..1---Account--standard and 2---Transaction---custom object. In the transaction one field is there i.e., Transaction type. So my question is i want to update a field on account object record based on Transaction Type. How can i achieve this using Triggers(Like Roll up summary fields).
Following is the example of populating Transaction record count on Account record based on Transaction Type(Let's say if transaction type='transact' then only count the record), you can also modify code to populate transaction field instead of record count :
1. Write a trigger on Transaction object for after insert/update/undelete events as per your need.
2. Iterate over Transaction records using Trigger.New and populate all account Id's in a set.(considering the Lookup/Master detail field name on Transaction is AccountId)
Set<Id> setAccountId = new Set<Id>();
for(Transaction objTransaction : Trigger.New){
setAccountId.add(objTransaction.AccountId);
}
3. Query Transaction Records by adding where clause for the set of account Id's and populate Account id and related Transactions.
Map<Id, List<Transactions>> mapAccountIdToTransactionList = new Map<Id, List<Transactions>>();
for(Transaction objTransaction : [Select Id, AccountId From Transaction where Transaction.AccountId :=setAccountId]){
if(mapAccountIdToTransactionList.containsKey(objTransaction.AccountId)){
mapAccountIdToTransactionList.get(objTransaction.AccountId).add(objTransaction);
}
else{
mapAccountIdToTransactionList.put(objTransaction.AccountId, new List<Transaction>{objTransaction};
}
}
4. Iterate over a Map and check individual transaction Record against transaction type and update account count field.
List<Account> lstAccount = new List<Account>();
for(String accId : mapAccountIdToTransactionList.keySet()){
integer count = 0;
List<Transaction> lstTransaction = mapAccountIdToTransactionList.get(accId);
if(lstTransaction!= null){
for(Transaction objTrans : lstTransaction){
if(objTrans.TrnsactionType='Transact'){
count++;
}
}
}
Account account = new Account();
account.Id = accId;
account.TransactionCount = count;
lstAccount.add(account);
}
try{
update lstAccount;
}
catch(Exception ex){
System.debug('Error : ' + ex.getMessage());
}
Please let me know if you have any further questions or concerns.