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
nareshnaresh 

can we write a class in trigger

Jagannatha Reddy BandaruJagannatha Reddy Bandaru
Hi Naresh,

we can't write a class in trigger directly ,
but we can call the class into trigger.

ex: class
public class classname
{
public static void display()
{
............
.............
}
}

in trigger:
trigger triggername on Object(events)
{
classname.display(trigger.new);
}

any doubts pls feel free to ask.
Thanks,
Jagan
jagan.srit@gmail.com
ramlakhanramlakhan
Hi Naresh,
Jagganath has explained very well.We don't need to write a class in a trigger.Each object shouldn't have more than one trigger.So what we do is we write trigger logic in a class(trigger handler) and then we call that class from the trigger.Each time you need to add /modify some trigger logic  
,you have to just make changes  to the class and include the trigger event in the trigger if previously not included.
Deepak Kumar ShyoranDeepak Kumar Shyoran
Yes we can write a class and a method inside a trigger. but generally  we are not using this approach as its not a good practice rather we write code for trigger in another class and call method of that class from trigger.
way to write class inside a trigger  ex ;
//Trigger to stop inserting Hindi Teacher
trigger Cannot_Insert_Hindi_Teacher on Contact (before update,before insert)
{
    //Add Error if teacher teaches Hindi
    for(Contact con :Trigger.new)
        if(con.Subject__c=='Hindi')
            con.addError('Hindi Teacher is Allready Exist');
    
   public class tempClass{
		public void tempClass() {
			System.debug('--Class inside Trigger') ;
		
		}
   }
}
If you want you can write method directly inside a class without class.
like 
 
//Trigger to stop inserting Hindi Teacher
trigger Cannot_Insert_Hindi_Teacher on Contact (before update,before insert)
{
    //Add Error if teacher teaches Hindi
    for(Contact con :Trigger.new)
        if(con.Subject__c=='Hindi')
            con.addError('Hindi Teacher is Allready Exist');
    
         public void tempClass() {
		System.debug('--Class inside Trigger') ;
	}
}

 
NITIN BANGARNITIN BANGAR

Hi ,

Can anyone tell me how to cover that class and its methods(inside a trigger) in a test class