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
kingsixkingsix 

When closed the Opportunity, close its Quotes automatically

Hello,

 

I wrote a trigger for Opportunity. I want to do 'When closed the Opportunity, close its Quotes automatically', but it didn't work. Please help to check the code, thanks!!

 

 

trigger QuoteClose on Opportunity(after insert, after update) {
Quote[] cList = new Quote[]{};
for(Opportunity opp : trigger.new)
{if (opp.StageName == 'Closed Won')
cList.add(new Quote(OpportunityId=opp.Id, Status = 'Close'));
}
if (cList != null && !cList.isEmpty())
Database.update(cList);
}

 

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

Since the Opportunity to Quote relation is One - Many, creating just one instance of Quote per Opprtunity wont do it. You will need to query for the quotes of the Opportunities and then update them.

 

 

trigger QuoteClose on Opportunity(after insert, after update) {
Quote[] cList = new Quote[]{};
Id[] oppIds = new List Id[]{};
for(Opportunity opp : trigger.new)
if (opp.StageName == 'Closed Won')
oppIds.add(opp.Id);
for(Quote quo : [Select Id, Name, Status, OpportunityId from Quote where OpportunityId IN :oppIds])
{
quo.Status = 'Closed';
cList.add(quo);
}
if (cList != null && !cList.isEmpty())
Database.update(cList);
}

 

All Answers

Ritesh AswaneyRitesh Aswaney

Since the Opportunity to Quote relation is One - Many, creating just one instance of Quote per Opprtunity wont do it. You will need to query for the quotes of the Opportunities and then update them.

 

 

trigger QuoteClose on Opportunity(after insert, after update) {
Quote[] cList = new Quote[]{};
Id[] oppIds = new List Id[]{};
for(Opportunity opp : trigger.new)
if (opp.StageName == 'Closed Won')
oppIds.add(opp.Id);
for(Quote quo : [Select Id, Name, Status, OpportunityId from Quote where OpportunityId IN :oppIds])
{
quo.Status = 'Closed';
cList.add(quo);
}
if (cList != null && !cList.isEmpty())
Database.update(cList);
}

 

This was selected as the best answer
kingsixkingsix

Thanks so much, it works.

Desland VandoDesland Vando

I'm receiving an erro rin the trigger... :(

Error: Compile Error: Unexpected token '['. at line 3 column 3