0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

取引先の所有者を変更した時に、商談の所有者を変更するトリガー

Posted at

簡単に例題となるような回答やブログ等が見つかると思いましたが、なかったのでサックと作成。

本当は既に終わった商談は対象にしないなど、要件の洗い出しが必要だと思います。

別の回答者さんは、プロセスビルダー押しでしたが、後々の変更を考えるとやっぱりApexトリガでしょう。
一括処理も考慮しやすいしね。

trigger UpdateAccountOpp on Account (after insert, after update) {
    
    Map<Id, Account> acOldMap = null;
    Map<Id, Account> acNewMap = new Map<Id, Account>(Trigger.new);
    if (Trigger.old != null) {
        acOldMap = new Map<Id, Account>(Trigger.old);        
    } else {
        acOldMap = new Map<Id, Account>();
    }
    
    Set<Id> AccountIdSet = new Set<Id>();
	List<Opportunity> updateOpportunityList = new List<Opportunity>();
    
    if (Trigger.isAfter) {
        for (Account ac: Trigger.new) {
            if (ac.RecordType.Name == 'ABC' ){
                Account oldAcc = (Account)acOldMap.get(ac.Id);
                if (oldAcc != null && ac.OwnerId != oldAcc.OwnerId){
                    AccountIdSet.add(ac.Id);
                }
            }            
        }//end of for
        
        List<Opportunity> OpportunityList = [SELECT Id,AccountId FROM Opportunity WHERE AccountId =: AccountIdSet];
        for (Opportunity opp : OpportunityList){
            Account acc = (Account)acNewMap.get(opp.AccountId);
            if (acc != null){
                Opportunity upopp = new Opportunity();
                upopp.Id = opp.Id;
                upopp.OwnerId = acc.OwnerId;
                updateOpportunityList.add(upopp);
            }
        }//end of for
        if (updateOpportunityList.size() > 0) update updateOpportunityList;
        
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?