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
RishuRishu 

Validation Rule using trigger

I have a requirement to throw an error using trigger:-
I have two object , object1 and object2 (child object) - MD Relationship
Object1 - stage field
 object2 - field 1 and field 2 ( Picklist field)
If the object1 has related record   where field 1 = "Closing"and field  2 = "Satisfied " then stage field of object1 should not be equal to Closing.
AnkaiahAnkaiah (Salesforce Developers) 
Hi Rishu, 

Object1 have multiple child records, which you have to consider?

Thanks!!
RishuRishu
Yes it has multiple child record
AnkaiahAnkaiah (Salesforce Developers) 
try with below code.
 
Trigger PreventstageUpdate on Parent__c(before update){

if(trigger.isinsert && trigger.Isbefore){

set<id> accids = new set<id>();
for(Parent__c con:trigger.new){
accids.add(con.id);
}

}
List<child__C> accliast = [SELECT id,field1__c,field2__c from child__c where parent__c=:accids AND field1__c='Closing' AND field2__c='Satisfied' ];

for(Parent__c con: trigger.new){
 if(accliast.size()>0 && con.stage=='closing'){

con.adderror('you cant select stage as closing');
}
}

}

If this helps, Please mark it as best answer.

Thanks!!
RishuRishu
Hi Ankaiah Thanks for the code
I wanted to write this in trigger handler.
​​​​​
AnkaiahAnkaiah (Salesforce Developers) 
try with below code.

Trigger:


    trigger PreventstageUpdate on Parent__c(before update)  
    {
 ParentTriggerHandler handler = new  ParentTriggerHandler();
	if(trigger.Isupdate && trigger.Isbefore){
        handler.updateStage(Trigger.new);  // Call method for update Parent__c field.

    }
}
Handler class:
public class ParentTriggerHandler
    {
		public void updateStage(List<Parent__c> plist)
		{

		set<id> accids = new set<id>();
		for(Parent__c con:plist){
		accids.add(con.id);
		}

		List<child__C> accliast = [SELECT id,field1__c,field2__c from child__c where parent__c=:accids AND field1__c='Closing' AND field2__c='Satisfied' ];

			for(Parent__c con: plist){
			 if(accliast.size()>0 && con.stage=='closing'){

			 con.adderror('you cant select stage as closing');
			 }
			}
		}		   
}

If this helps, Please mark it as best answer.

Thanks!!