[Salesforce] Apex - Trigger

__Dev_1·2023년 10월 27일
0

Salesforce

목록 보기
13/15
post-thumbnail

🍒 Trigger 기본 문법.

trigger 트리거 이름 on 트리거에 대상이 될 Sobj( trigger action)

🍒 Trigger 구현.

🧶 Trigger
trigger AccountTrigger on Account (after insert, before update ) {

    system.debug('============= Trigger Start =============');

    if(Trigger.isInsert){
        if(Trigger.isBefore){

        }else if(Trigger.isAfter){
            AccountTriggerHandler.isnertRecord(Trigger.new);
        }
    }

    if(Trigger.isUpdate){
        if(Trigger.isBefore){
            AccountTriggerHandler.updateTriggerRecord(Trigger.new);
            AccountTriggerHandler.updatePhone(Trigger.oldMap, Trigger.new);
        }else if(Trigger.isAfter){
            // AccountTriggerHandler.afterUpdateAccList(Trigger.new);
        }
    }
}   


🧶AccountTriggerHandler
public class AccountTriggerHandler {
    
    public static void isnertRecord(List<Account> accList){
        system.debug('accList : ' + accList);

        //=========== 오답 ===========
        // List<Account> acc = new List<Account>();
        // acc.Rating = 'Warm';

        // insert acc;
        //=========== 오답 ===========

        //Account 가 타입인 인스턴스에 , 선언한 Account의 타입인 List 에 담아서 insert
        List<Account> insertAcc = new List<Account>();
        List<Contact> conList = new List<Contact>();

        for(Account a : accList){

            //Account 타입인 인스턴스를 생성
            Account acc = new Account();
            acc.Name = a.Name;
            acc.Rating = 'Warm' ;

            insertAcc.add(acc);
            system.debug('@@@@ insertAcc : ' + insertAcc);

            Contact con = new Contact();
            con.LastName = a.Name;
            con.Level__c = 'Secondary';

            conList.add(con);
        }

        if(!insertAcc.isEmpty()){
            insert conList;
            // ** 이미 account 에 insert 액션이 취해졌기 떄문에 별다른 action 을 취하지 않아도 됨.
            //insert insertAcc; 
        }
    }

    public static void updateTriggerRecord(List<Account> beforeUpdateAccList){
        system.debug('========== Before Update ==========');
        system.debug('updateAccList : ' + beforeUpdateAccList);

        for(Account a : beforeUpdateAccList){
            System.debug('a.Rating : ' + a.Rating);
            a.Rating = 'Hot';
        }
    }

    public static void updatePhone(Map<Id,Account> oldAccountMap ,List<Account> afterAccountList){
        system.debug('========== After Update ==========');
        system.debug('oldAccountMap : ' + oldAccountMap);
        system.debug('afterAccountList : ' + afterAccountList);
        
         for( Account acc : afterAccountList){
             if(acc.Rating != oldAccountMap.get(acc.Id).Rating){
                 acc.Phone = '1234';
             }else{
                 acc.Phone = '5678';
             }
        }
    }
}
profile
메모장 :)

0개의 댓글