The line which is commented is giving me a DML exception dont know why? i think it is not getting id there.. I know i am asking too many questions or may be silly questions but i want some clear point on these.
public static void brokeragePortal(List<Candidate_Brokerage__c> candBrokRecords){
Map<id, Contact> contListMap = new Map<id, Contact>();
Map<id, Account> accListMap = new Map<id, Account>();
Map<id, Account> newAccListMap = new Map<id, Account>();
Map<id, Task> taskListMap = new Map<id, Task>();
for(Candidate_Brokerage__c brokerCand: candBrokRecords){
if(brokerCand.Brokerage__c != NULL){
Account acc = new Account(name = 'Brokerage Account');
if(!accListMap.containsKey(brokerCand.id)){
accListMap.put(brokerCand.id, acc);
}
}
}
if(accListMap.values().size()>0){
insert accListMap.values();
}
for(Candidate_Brokerage__c cand: candBrokRecords){
if(cand.Brokerage__c != NULL && cand.Manage_Brokerage__c != NULL){
Account manageBrokAcc = new Account(name = 'Manage Brokerage Account');
if(accListMap.containsKey(cand.id)){
manageBrokAcc.ParentId = accListMap.get(cand.id).id;
}
if(!newAccListMap.containsKey(cand.id)){
newAccListMap.put(cand.id, manageBrokAcc);
}
Contact newContact = new Contact(lastName = 'John Doe');
if(!contListMap.containsKey(cand.id)){
contListMap.put(cand.id, newContact);
}
}
}
if(newAccListMap.values().size()>0){
insert newAccListMap.values();
}
if(contListMap.values().size()>0){
insert contListMap.values();
}
for(Candidate_Brokerage__c cand: candBrokRecords){
if(cand.Brokerage__c != NULL && cand.Manage_Brokerage__c != NULL){
Task newTask = new Task();
if(contListMap.containsKey(cand.Id)){
newTask.WhoId = contListMap.get(cand.Id).id;
}
//newTask.WhatId = cand.id;
newTask.Subject = 'Portal Contact Setup';
if(!taskListMap.containsKey(cand.Id)){
taskListMap.put(cand.id, newTask);
}
}
}
if(taskListMap.values().size()>0){
insert taskListMap.values();
}
}
//Trigger
trigger BrokerageTrigger on Candidate_Brokerage__c (after insert) {
if(Trigger.isAfter && Trigger.isInsert){
AccountContact.brokeragePortal(Trigger.new);
}
}
Hi Nabeel,You can achieve functionalities 1 and 2 in before insert as well but always try to do actions in the after trigger event when you are dealing with other records than that in transaction.Coming to your query - Why can't we do these in before trigger, I would specifically answer it for the points 3 and 4.The reason being you need Candidate__c Id to lookup with Contact and task objects, which you can only get in after insert, as the IDs are not assigned to the records in before trigger context.