+ Start a Discussion
Lavanya Ponniah 3Lavanya Ponniah 3 

How to write trigger for order for the below scenario?

In the order i have a custom field as order no, if i create a first record i enter the order no.
For the next time when i create record for the same contract number, the order no have to insert.How can i do that

Can anyone provide code please.
Best Answer chosen by Lavanya Ponniah 3
SethuSethu
Hi Lavanya,

Use the below code

trigger insertOrderNumber on Order (before insert, before update) 
{
map<id,integer> omap = new map<id,integer>();
set<id> contractnumber = new set<id>();

for(Order newOrder : Trigger.new)
{
   contractnumber.add(newOrder.Contractid); 
}
for(Order o : [SELECT id, Order_Num__c, Contractid FROM Order WHERE Contractid IN : contractnumber])
{
   omap.put(o.contractid, (integer)o.Order_Num__c);
}
for(Order newOrder : Trigger.new)
{
    if(omap.containskey(newOrder.contractid))
    newOrder.Order_Num__c = omap.get(newOrder.contractid);
}
}

All Answers

SethuSethu
Hi Lavanya,

Use the below code

trigger insertOrderNumber on Order (before insert, before update) 
{
map<id,integer> omap = new map<id,integer>();
set<id> contractnumber = new set<id>();

for(Order newOrder : Trigger.new)
{
   contractnumber.add(newOrder.Contractid); 
}
for(Order o : [SELECT id, Order_Num__c, Contractid FROM Order WHERE Contractid IN : contractnumber])
{
   omap.put(o.contractid, (integer)o.Order_Num__c);
}
for(Order newOrder : Trigger.new)
{
    if(omap.containskey(newOrder.contractid))
    newOrder.Order_Num__c = omap.get(newOrder.contractid);
}
}
This was selected as the best answer
Lavanya Ponniah 3Lavanya Ponniah 3
Hi Sethu

It really works for me.Thank you so much.