You need to sign in to do that
Don't have an account?
Med Usa1
Trigger : How to set a value to a field
Hello,
I want to add a value to a field on a before insert trigger.
I want to make an auto number with different conditions so to select the last number and set the value = last + 1 to the field.
Where can I find a documentation for that ? To add a value to a field on before insert ?
I don't know how to recover this value :
Opportunity q_opp = [SELECT MAX(Opp_Num__c) FROM Opportunity];
and what it will return if there is no record in the table.
Thank you.
Would you like to elaborate the problem little more??
Hi MedUsa1
This is how you'd get the max:
SELECT Opp_Num__c FROM Opportunity ORDER BY Opp_Num__c DESC LIMIT 1
..But I'm not aware of the ability to modify an autonumber value -- you can change the format, but that will only be for subsequent records.
Hi,
when ever you are going to create any record you will add 1 to that value. Since your system have these value already exist. You have to simply make a select query in which you have to simply make query with order by clause like created by date desc limit 1. It will always give you the latest value exit in that field. Now use that value inside your trigger. Try the below code as reference:
Trigger Autonumber on CustomObject(before insert)
{
for(CustomObject c: trigger.new)
{
list<CustomObject> cNew=[select id,AutonumberField__c,condition__c from CustomObject order by createddate desc limit 1];
if(cNew.size() > 0)
{
if(cNew[0].condition__c =='abc')
{
c.AutonumberField__c= cNew[0].AutonumberField__c + 1;
}
////////// Similarly for other conditions //////////////////////
}
else
{
if(cNew[0].condition__c =='abc')
{
c.AutonumberField__c= 'abc-00000';
}
////////// Similarly for other conditions //////////////////////
}
}
}
Kevin has already mentioned the query to find the max value. So you can proceed like this.
Trigger maxValueUpdate on opportunity(before update, before insert)
{
Opportunity opp = [SELECT Opp_Num__c FROM Opportunity ORDER BY Opp_Num__c DESC LIMIT 1];
Opportunity curOpp = [ select id from opportunity where id : trigger.new limit 1]; // you can bulkify it later for multiple opportunities
if ( trigger.isInsert)
{
if(opp.Opp_Num__c == null)
CurOpp.Opp_Num__c = 1 ;
}
if(trigger.isupdate)
{
if(opp.Opp_Num__c == null)
CurOpp.Opp_Num__c = 1 ;
else
CurOpp.Opp_Num__c = opp.Opp_Num__c + 1 ;
}
}
Hello,
Thanks you for your answers.
I just see your solutions and I have already made a trigger but I have a pb :
The pb : groupResults.size() always > 0 even if there is no records returned by the query and it can't go into the "Else" block.
Could you tell me where is the pb ?
Thank you.