0

I want to Update Website(custom field) in opportunity by filling the same value in Website(standard field) in Account.Here by entering the value in Account website it should populate in the opportunity website field with same value.using trigger how can i do thistrigger

accountTrigger on Account (after Insert, after Update) { 
    List <Account> acc = new <Account>(); 
    acc = trigger.new(); 
    List <Opportunity> opp; 
    for(Account acc:acclist) { 
        opp=[select id,Website__c from Opportunity where Account id=acc.id]          
        for(Opportunity op:opp) { 
            op.Website__c=ac.Website; 
        } 
     }
 }
2
  • 1
    Can you show what you've attempted in writing the trigger on the Opportunity object to retrieve the value from the parent Account object and writing that value to the Website__c field on the Opportunity record?
    – Mark Pond
    Commented Dec 10, 2013 at 6:08
  • trigger accountTrigger on Account (after Insert, after Update) { List <Account> acc = new <Account>(); acc = trigger.new(); List <Opportunity> opp; for(Account acc:acclist) { opp=[select id,Website__c from Opportunity where Account id=acc.id] for(Opportunity op:opp) { op.Website__c=ac.Website; } }
    – user4772
    Commented Dec 10, 2013 at 7:38

2 Answers 2

2

You should not put your SOQL inside of a for loop, because you will hit governor limits as soon as your list of Accounts becomes larger than 100. See Understanding Execution Governors and Limits for more info on governor limits.

You can use the Trigger.newMap's keySet to query for all of the Opportunities and then update them. You can take advantage of the fact that the Account that you query back as part of the Opportunity query will have the new value set at the time of the after update.

Note that you do not have to handle after insert, since it will be impossible for Opportunities to exist at the time that their parent Account is being inserted.

trigger AccountTrigger on Account (after update) {
    List<Opportunity> opps = [
        Select Id, Website__c, Account.Website
        From Opportunity
        Where AccountId In :Trigger.newMap.keySet()
    ];
    for (Opportunity opp : opps) {
        opp.Website__c = opp.Account.Website;
    }
    update opps;
}

Sidenote: You could also just query using Trigger.new directly and not use Trigger.newMap.keySet() as it is legal syntax to use a list of sObjects with IDs as part of an In clause. So you could have the following as your where clause. Either one will work.

Where AccountId In :Trigger.new
0

I don't think any need for trigger in this case, Cross object formula will do the task here.

1
  • Welcome to SFSE Amit, can you add an example of what the formula would be? I know it's simple but it helps :)
    – Matt Lacey
    Commented Jul 21, 2015 at 3:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .