I have a requirement that after inserting a record in Campaign Account(Custom Object lookup with Account) it should check the Campaign Account Name with opportunities related to the Account. I was able to achieve the functionality using the trigger. But I wanted to optimize my code so can someone help me with my code.
//Helper for Trigger
public class CreateOppAfterCAInsertionHelper {
**public string name;**
**public Id accId;**
public void insertOpp(List<Campaign_Account__c> campaignAccList) {
Set<Id> accIds = new Set<Id>();
List<Opportunity> oppList = new List<Opportunity>();
List<Opportunity> updatedOpps = new List<Opportunity>();
for(Campaign_Account__c campAcc : campaignAccList) {
if(campAcc.Account__c != NULL) {
accIds.add(campAcc.Account__c);
**name = campAcc.Name;**
**accId = campAcc.Account__c;**
}
}
oppList = [SELECT Name, AccountId, Count__c
FROM Opportunity
WHERE AccountId IN:accIds AND Name =: name];
if(oppList.size() > 0) {
for(Opportunity opp : oppList) {
opp.Count__c = opp.Count__c + 1;
updatedOpps.add(opp);
}
}
if(oppList.size() == 0) {
Opportunity newOpp = new Opportunity();
newOpp.Name = name;
newOpp.StageName = 'Prospecting';
newOpp.CloseDate = date.today();
newOpp.AccountId = accId;
insert newOpp;
}
if(updatedOpps.size() > 0) {
update updatedOpps;
}
}
}
I want to avoid the highlighted lines. Need help thank you...