+ Start a Discussion
Ricardo ManaiaRicardo Manaia 

Apex trigger - a couple of questions

Hi everyone,

So this is my first attempt at writing an Apex trigger and it seems to be working fine in the Sandbox.
I've now got a couple of questions that I'm hoping you could help me with:

1. You can see the trigger is simple enough, just a bunch of IF statements but it does the job. As I'm only starting in this area I'm unsure if I took the right approach and if it even complies with best practices used with Apex triggers.
Could or should I have used FOR loops instead? Would any code variations be more suitable?
Are there any risks of falling in an endless loop?

2. How do I go about creating Test Classes for this trigger?

Any help with the above is welcome! Thanks a million guys!

Code snippet
NaveenReddyNaveenReddy
Hi Ricardo,

  1). Salesforce recommends to not use hard coding Ids.
     Instead use like this
    
Select Id From  BusinessHours Where Name='Test'

2). Use Else If blocks so that if one IF condition becomes true it wont check the other this is good programming practice.

Thanks,
Naveen.
geeta garggeeta garg
Hi Ricardo Manaia,

Firstly you click on setup and enter apex class in quick search.Then create new class.
@isTest
public class UpdateNextupdateTimeTest {
static testMethod void validateHelloWorld() {
//insert the case for all if condition..
} }

Then save it.Then click on run test and select your test class and run it.
Thanks,
Geeta Garg
 
venkat-Dvenkat-D
I wouldnt recommend hardcoding those many values in the trigger. Best way can be to have custom metadta type with information like
Status, SLA, Product, NO of hours. Then get the data from metadata and use it to calculate or validate your things. this way everytime sla chagnes you dont have to update trigger.
Ricardo ManaiaRicardo Manaia
Thank you all for your input! I'm going to tweak the trigger based on your suggestions and I'll get back to you. I might have a few more questions after that... hopefully not too many :-)

I'll also give it a go on the Test Class following geeta garg's comment.

Thanks again!
Ricardo ManaiaRicardo Manaia
Hi there,

So I had a few attempts at creating a test class for this but failed miserably...

To keep things simple could you give me an example of a test class for the below trigger so I can then try to work my way through?

trigger UpdateNextUpdateTime on Case (before insert, before update) {
    BusinessHours bh = [SELECT Id FROM BusinessHours WHERE id='01m20000000PbKG'];
    for( Case c : Trigger.new )
    {   
        If (c.Status == 'Assigned' && 
            c.SLA__c == 'P1'){
            c.Next_Update_Time__c = c.Next_Update_Time_All_Hours__c;}
        If (c.Status == 'Assigned' &&
            c.SLA__c == 'P2'){
            c.Next_Update_Time__c = BusinessHours.add(bh.Id, c.Assigned_Date_Time__c, 36000000);}
    }
}


Thanks again!