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
anillllanillll 

incrementing a number field when opportunity is closed won

I have a custom field in Opportunity is Auto_Number__c

 

i have a trigger like this

trigger updateactive on Opportunity(before insert){



for(Opportunity c : Trigger.new){

if(c.StageName == 'Closed Won')
c.Auto_Number__c=c.Auto_Number__c+1;

}

}

 I want to increment the old record Auto_Number__c and update like2,3,4 etc  like that when opportunity is closed won

 

AsitM9AsitM9
trigger updateactive on Opportunity(before insert){

List<Opportunity> OpList=[SELECT Auto_Number__c FROM Opportunity ORDER BY Auto_Number__c  DESC];

for(Opportunity c : Trigger.new){

if(c.StageName == 'Closed Won')
c.Auto_Number__c=OpList[0].Auto_Number__c+1;

}

}

 

deepabalisfdcdeepabalisfdc

Hi ,

You ant to update auto number field based on which last value?I assume from your code, that you want to increment present value.
Trigger seems correct, you need to add update condiiton also in trigger

trigger updateActive on Opportunity(before insert,before update){
for(Opportunity c : Trigger.new){
    if(c.StageName == 'Closed Won')
       c.Auto_Number__c = c.Auto_Number__c + 1;
    }
}
anillllanillll

yes based on the previous value

anillllanillll

Its giving an error 

 

caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.updateactive: line 7, column 1

Rajesh SriramuluRajesh Sriramulu

HI,

 

Try this

 

AggregateResult[] groupedResults = [SELECT count(Id)aver FROM Opportunity where StageName=:'Closed Won'];
   system.debug('groupedResults '+groupedResults+1 );

 

Regards,

Rajesh.

deepabalisfdcdeepabalisfdc

Auto_Number is a number field. I think the record you are creating or updating has no value at thi sfield first.
trigger updateActive on Opportunity(before insert,before update){
for(Opportunity c : Trigger.new){
    if(c.StageName == 'Closed Won' && c.Auto_Number__c != null)
       c.Auto_Number__c = c.Auto_Number__c + 1;
    }
}

Either check null or give default 0 to this field.

Laxman RaoLaxman Rao

trigger updateactive on Opportunity(before insert){

integer autoNumber = 0;
List<Opportunity> OpList = [SELECT Auto_Number__c FROM Opportunity ORDER BY Auto_Number__c DESC LIMIT 1];

if(!OpList.isEmpty()) {
autoNumber = OpList[0].Auto_Number__c;
}

for(Opportunity c : Trigger.new){

if(c.StageName == 'Closed Won')
c.Auto_Number__c = ++autoNumber;

}

}

Bhawani SharmaBhawani Sharma
Create a roll up summary field on account.
Formula: Count(Oppotunity) and criteria is Stage = "Closed WOn"4

Now create a formula field on Opportunity and fetch that value from account using Account.RollupSummary field