function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Board salesforceBoard salesforce 

field update on Opportunity

Hi All,

An account can have 10 Opportunities ,when i open a opportunity and change the stage to  Closed won then other 9 Opportunities has to be  Updated closed Lost automatically.

Please help on this.
Thanks ,
 
Best Answer chosen by Board salesforce
Charisse de BelenCharisse de Belen
Hello,

Try this trigger:
trigger CloseSiblingOpportunities on Opportunity (before insert, before update) {
	
    Set<Id> accountIds = new Set<Id>();
    Set<Id> oppIds = new Set<Id>();
    
    for(Opportunity opp : Trigger.new) {
        if(opp.StageName == 'Closed Won') {
            accountIds.add(opp.AccountId);
            oppIds.add(opp.Id);
        }
    }
    
    if (accountIds.size() > 0) {      
        List<Opportunity> siblingOpps = new List<Opportunity>();
        for(Opportunity sibling : [SELECT Id, StageName FROM Opportunity
                                   WHERE AccountId IN :accountIds
                                   AND Id <> :oppIds]) {
            sibling.StageName = 'Closed Lost';
            siblingOpps.add(sibling);
        }
        update siblingOpps;
    }
    
}

All Answers

Charisse de BelenCharisse de Belen
Hello,

Try this trigger:
trigger CloseSiblingOpportunities on Opportunity (before insert, before update) {
	
    Set<Id> accountIds = new Set<Id>();
    Set<Id> oppIds = new Set<Id>();
    
    for(Opportunity opp : Trigger.new) {
        if(opp.StageName == 'Closed Won') {
            accountIds.add(opp.AccountId);
            oppIds.add(opp.Id);
        }
    }
    
    if (accountIds.size() > 0) {      
        List<Opportunity> siblingOpps = new List<Opportunity>();
        for(Opportunity sibling : [SELECT Id, StageName FROM Opportunity
                                   WHERE AccountId IN :accountIds
                                   AND Id <> :oppIds]) {
            sibling.StageName = 'Closed Lost';
            siblingOpps.add(sibling);
        }
        update siblingOpps;
    }
    
}
This was selected as the best answer
Board salesforceBoard salesforce
HI Charisse de Belen,

yes i worked same on it .Now i have stageName Picklist field on account level too , I have to update 'Closed won'  in Account .


Thanks ,
Ramesh
Charisse de BelenCharisse de Belen
Hi Ramesh,

Just add another SOQL query for loop that selects all the Accounts in accountIds and updates them to change the Stage Name field to 'Closed Won'.