You need to sign in to do that
Don't have an account?
How do I get createdDate in variable in BeforeInsert Trigger?
Hello Developers!
I am trying to write a trigger on opportunity where it would throw an error when user exceeds 10,000 daily limit of opportunity amount. One sales rep can create number of opportunities up to the amount where Amount can not exceed 10,000 per day.
Here is my logic: When there is a new record inserted in system, I am getting that record's userId, and createdDate in variables. Then I have a SOQL which fetches the all opportunities in database which is created by that user and on the today's date (I am not too sure my SOQL in the code below). Once the records are fetched, I have a loop which sumes up the amount from the fetched opportunities in SOQL and if that sum is greater then 10,000, I am throwing an error.
Trigger TenThousandDollarsLimit on Opportunity(Before Insert){ // We need to write a trigger so one user can not create more then // $10,000 of opportunity per day. User OppOwner; ID OppOwnerID; Double AmountSum; Date TodaysDate; For(Opportunity opp: Trigger.New){ OppOwner = opp.Owner; OppOwnerID = opp.OwnerId; TodaysDate = opp.createdDate.date(); List<Opportunity> opps; opps = [Select Id, Amount FROM Opportunity WHERE OwnerId = :OppOwnerId AND CreatedDate = :TodaysDate]; For(Integer I = 0; I < opps.size(); I++) { AmountSum = opps[I].Amount; } If (AmountSum > 10000){ opp.addError('You have exceed your daily limit of $10,000'); } else{ // do nothing } } }Here is an Error Message while saving the first record:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger TenThousandDollarsLimit caused an unexpected exception, contact your administrator: TenThousandDollarsLimit: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.TenThousandDollarsLimit: line 14, column 1
Thank you for the help guys!
Govind,
Sorry it what happens when we write code in a notepad and not in Salesforce where we can compile and check. My bad, following is the updated code. TRIED and TESTED
Thanks
Vivian
All Answers
Hi Govind,
Try this
I first find all owner id's and put the current amount in map of Ownerid and amount.
Aggregate query finds today's Opportunities grouped by the Owner Id. This aggregate result can now be used along with the map to find total and raise error if it exceeds 10000.
Thanks
Vivian
I am getting a compile Error:
Method does not exist or incorrect signature: void containskey(Object) from the type Map<Id,Decimal> at line 25 column 25
Thank you!
Govind,
Sorry it what happens when we write code in a notepad and not in Salesforce where we can compile and check. My bad, following is the updated code. TRIED and TESTED
Thanks
Vivian
Hope it results useful,
Regards