You need to sign in to do that
Don't have an account?
How to use apex trigger like validation rule (before inser or update)
Hi ,
i am new to apex programming.
my requirement is like below
opportunity can have Tradin plan
Each opportunity can have n number of trading plan but
all trading pan amount can not greater than the opportunity amount .
to check the sum of trading plan amount whether it is greater or less
in validation rules it is not possible so i thought i can write apex trigger
but i don't know how to stop data insertion if codition fails in apex trigger .
below i written apes trigger before insert
please help me on this
trigger TradingPlanInsert on Opportunity_Trading_Plan__c (before insert)
{
Id opptID;
double oppAmount = 0;
double oppTplanAmount= 0;
for(Opportunity_Trading_Plan__c newTradinPlanObj: Trigger.new)
{
opptID = newTradinPlanObj.Opportunity_trading__c;
oppTplanAmount = oppTplanAmount + newTradinPlanObj.Plan_Amount__c;
}
Opportunity_Trading_Plan__c[] oppTradingobj = [Select Id, Name, CurrencyIsoCode, Opportunity_trading__c,
Plan_Amount__c, Trading_Received_Date__c, Milestone__c, Description__c, GM__c
FROM Opportunity_Trading_Plan__c where Opportunity_trading__c = :opptID];
for(Opportunity_Trading_Plan__c oppTexistinObj : oppTradingobj )
{
oppTplanAmount = oppTplanAmount + oppTexistinObj.Plan_Amount__c;
}
Opportunity[] oppobj = [Select Id, StageName, Amount, CloseDate, Type, CurrencyIsoCode FROM Opportunity where ID =:opptID];
for(Opportunity oppdetailsObj : oppobj )
{
oppAmount = oppdetailsObj.Amount;
}
if (oppAmount < oppTplanAmount )
{
System.Debug('Trading plan amount more than opportunity amount ');
}
}
If you use the addError method on the sobject(s) that the trigger is working on, the insert will fail.
Check out the Triggers section of the Apex Developer's Guide.
i will create a new field in opportunity named like TotalTradinPlanAmount with type Roll-Up Summary .
it can keep all the tradin plan amount so far and then it would be easy to do just in validation rule on page side
when user create a new tradin plan record. you do not have to do this in trigger at all.
validation fired condition like : if opp.TotalTradinPlanAmount + opp.newtradinplan.amount >opp.amount .
i did not try just a idea here. please let me konw if it works. thanks
Hi , thanks for your suggession .
as per your suggession i try to created Roll-Up Summary filed in opportunity
but i am not able to create roll-up summary filed on currency data type (trading plan amount)
so what i did is i changed trading plan amount data type to number
then i am able to create roll up summary filed in opportunity
but my validation rule is not firing because
if (number data type > currency data type )
so it is failing
with addError i used but writing apex i am not interested is ther any other way please help me
Trigger.new[i].addError('Message:Trading plan amount more than opportunity amount:MessageEnd');
i used addError and it is working
but while running unit test code coverage time it is showing red colour
i am getting
public class AP04
2
{
3
7
public static void addNiceRef(Opportunity[] oppObj)
4
{
5
7
String OppDivisionCode;
6
7
Integer refCountValue = 1000 ;
7
7
for (Opportunity getoppObj1:oppObj)
8
{
9
1038
OppDivisionCode = getoppObj1.Division_Code__c ;
10
11
}
12
7
if(OppDivisionCode != null)
13
{
14
0
AggregateResult[] groupedResults = [select Max(RefNumCount__c) refnum from Opportunity where Division_Code__c = :OppDivisionCode group by Division_Code__c ];
15
0
for (AggregateResult ar : groupedResults)
16
{
17
0
if (String.valueOf(ar.get('refnum')) != null)
18
{
19
0
refCountValue = Integer.valueOf(String.valueOf(ar.get('refnum')));
20
}
21
}
22
0
for(Opportunity getoppObj2: oppObj)
23
{
24
0
getoppObj2.RefNumCount__c = refCountValue + 1;
25
0
getoppObj2.OLDNICENBR__C = OppDivisionCode + '' + getoppObj2.RefNumCount__c ;
26
}
27
}
28
29
30
}
31
15
public static void updateNiceRef(Opportunity[] oppObj)
32
{
33
15
String OpporunityID;
34
15
String OppDivisionCode;
35
15
Integer refCountValue = 1000 ;
36
15
Integer RecordCount = 0;
37
15
Integer tradingPlanCount = 0;
38
15
for (Opportunity getoppObj1:oppObj)
39
{
40
2336
OppDivisionCode = getoppObj1.Division_Code__c ;
41
2336
OpporunityID = getoppObj1.ID;
42
}
43
44
15
tradingPlanCount = [Select COUNT() from Opportunity_Trading_Plan__c where Opportunity_trading__c = :OpporunityID ];
45
46
15
RecordCount = [Select Count() from opportunity WHERE ID = :OpporunityID and Division_Code__c =:OppDivisionCode ];
47
15
if(RecordCount == 0)
48
{
49
0
AggregateResult[] groupedResults = [select Max(RefNumCount__c) refnum from Opportunity where Division_Code__c =:OppDivisionCode group by Division_Code__c];
50
0
for (AggregateResult ar : groupedResults)
51
{
52
0
if (String.valueOf(ar.get('refnum')) != null)
53
{
54
0
refCountValue = Integer.valueOf(String.valueOf(ar.get('refnum')));
55
}
56
}
57
}
58
59
15
for(Opportunity getoppObj2: oppObj)
60
{
61
4672
If(OppDivisionCode == null)
62
{
63
2336
getoppObj2.OLDNICENBR__C = null;
64
2336
getoppObj2.RefNumCount__c = 0;
65
}
66
else
67
{
68
0
getoppObj2.RefNumCount__c = refCountValue + 1;
69
0
getoppObj2.OLDNICENBR__C = OppDivisionCode + '' + getoppObj2.RefNumCount__c ;
70
}
71
72
2336
if ( (tradingPlanCount > 0) && getoppObj2.Trading_Plan__c == 'No')
73
{
74
0
getoppObj2.Trading_Plan__c.addError('Trading plan exist to this opportunity so you can not set to No');
75
76
}
77
}
78
79
80
81
}
82
}
while rumning unit test on above code why i am getting code coverage 62% and it is showing in 14 to 19 lines and
49 to 54 with red colour why it is showning
@istest
private class Test_AP04_AP05 {
private static testMethod void TestAP04(){
List<Opportunity> myOpportunityList1=new List<Opportunity>();
List<Opportunity> myOpportunityList2=new List<Opportunity>();
for(Integer i=0;i<100;i++){
myOpportunityList1.add(new Opportunity(name='_',StageName='_',CloseDate=date.today(),MarketSegment__c = 'Metals',Market_Community__c ='Latin_America',Division_Code__c = 'UKTY2',Amount=0,TotalGM__c=0));
myOpportunityList1.add(new Opportunity(name='_',StageName='_',CloseDate=date.today(),MarketSegment__c = 'Metals',Market_Community__c ='Latin_America',Division_Code__c = ''));
}
Database.Insert(myOpportunityList1);
for(Integer i=0;i<200;i++)myOpportunityList2.add(new Opportunity(name='_',StageName='_',CloseDate=date.today(),MarketSegment__c = 'Metals',Market_Community__c ='Latin_America',Division_Code__c = 'UKTY2',Amount=i,TotalGM__c=24,TPOpptyLink__c=myOpportunityList1[i].Id));
Test.startTest();
Database.insert(myOpportunityList2);
for(Opportunity o:myOpportunityList2)o.Amount+=1000.00;
Database.Update(myOpportunityList2);
Test.stopTest();
}
}
this my test call and this will satisfy the condition because i am insering with using division code
so condition will be success in update time
If you make Transactions with the financial instruments offered on this Website, you might incur substantial losses or even lose everything in your Account.
Trading (https://vfxalert.com/mobile?utm_campaign=SEO&utm_source=forums&utm_content=vfxalert_mobile/)