function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nandhini S 3Nandhini S 3 

need help on a before update trigger

Hi guys,
I need to create a trigger to throw error for the below scenarion...can someone help me with this.
Object1 is parent and Object2 is child. There is a picklist field 'Role' in Object2 with values ('A','B','C'). Object1 can have only one Object2 record with the same role.
If an Object1 has two Object2 child records.First record with Role = 'A' and second record with Role = 'B'. If the second record is updated to Role = 'A' then an error should be thrown.
How can i write a before update trigger to throw error.
CharuDuttCharuDutt
Hii Nandhini
Try Below Trigger
Object1 = 'Account'
Object2 = 'Contact'

trigger TestTrigger on Contact (before insert ,before update) {
    set<Id> lstid  = new set<id>();
    if(trigger.IsBefore){
        if(Trigger.IsInsert){
            for(Contact bc : Trigger.new){
                if(bc.AccountId != null){
                    lstid.add(bc.AccountId);
                }
            }
        }
        if(trigger.IsUpdate){
            for(Contact bc : Trigger.new){
                if(bc.AccountId != null && bc.AccountId!= Trigger.oldMap.get(bc.Id).AccountId){
                    lstid.add(bc.AccountId);
                }
            }
        }
    }
    
    list<Contact> lstbc = [Select Id,AccountId,pickval__c From Contact where 
                                    AccountId in :lstid And 
                                    (Role__c = 'A' or Role__c = 'B' or 
                                     Role__c = 'C')];
    for(Contact bc2 : Trigger.new){
        system.debug(lstbc.size());
        system.debug(lstbc);
        if(lstbc.size()==3){
            bc2.adderror('Error');
        }
            }
        

}
Please Mark It As Best Answer If It Helps
Thank You!

 
Nandhini S 3Nandhini S 3
Hi CharuDutt,

Thanks for replying. For my scenario, error should be thrown, if there is already a related contact record with Role ='A' and the other related contact record Role is updated to 'A'. There should be only one related records with 'A' role.

Thanks
CharuDuttCharuDutt
Ya
Thats The Code Doing
If Account Already Have Three Contact With Role A & B & C Now If We Insert/update Contact With Same Account With Role Either A & B & C gives error 
Nandhini S 3Nandhini S 3
Hi CharuDutt,

the Account maynot have three contacts with Role A,B,C. It can have jus two contacts with A and B role, When the contact with B role is updated to A role, then the error should be thrown