+ Start a Discussion
SUMANTH ELLURUSUMANTH ELLURU 

only one primary oppurtunity for an account

Create an insert/update trigger on Opportunity such that if the opportunity is Primary, then make all other opportunities for that account as non-primary.

Hi
I am new to sfdc. i want the implementation of trigger logic in apex class. i have tried by writing logic which is shown below. iam getting error of creating apex class. can anyone help me.
Apex class:
public class Oppurtunity{
    public static void display()
{
 
 List<Id> accID = new List<Id>();
    for(Oppurtunity opp : trigger.new)
{
        if(opp.accountId != null){
            accID.add(opp.accountId);
        }
    }

    List<account> acc = [select id, (select id, IsPrimary__c FROM Opportunity where IsPrimary__c = true) from Account WHERE Id In: accID];
 Map<id, boolean> bool = new map<id,boolean>();
    for(account a : acc){
        bool.put(a.id, a.Oppurtunities.size()>0 ? true : false);
    }

    for(Oppurtunity opp : trigger.new)
{
        if(bool.get(opp.AccountId) == true)
{
            c.addError('no more primary Oppurtunities');
        }
    }


        
    }

}
Trigger:
trigger checkaccount1 on Opportunity(before insert, before update)
{
classname.display(trigger.new);
}
Tej PalTej Pal
Hi SUMANTH,

Please use below code:
trigger OpportunityTrigger on Opportunity(after insert, after update){
	set<string> accIds = new set<string>();
	set<string> opIds = new set<string>();
	for(Opportunity o: trigger.new){
		if(o.IsPrimary__c){
			opIds.add(o.Id);
			accIds.add(o.AccountId);
		}
	}
	
	list<Opportunity> ops = new list<Opportunity>();
	for(Opportunity o: [select id, IsPrimary__c from Opportunity where Id NOT IN : opIds AND AccountId IN : accIds]){
		o.IsPrimary__c = false;
		ops.add(o);
	}
	
	if(ops.size() > 0){
		update ops;
	}
}
If this answers your question mark Best Answer it as solution and then hit Like!