0

How can I make more methods in this Helper class, not just public static void? I also need a method for checking the update of Stage__c field (when we update another fields - Trigger shouldn't be started).

Helper:

public with sharing class JobTriggerHelper {

public static void create(List<Job__c> jobList){

    List<Task> taskList = new List<Task>();

    for(Job__c job : jobList){ 
        if(job.Stage__c == 'Closed'){
            Task t = new Task(
                 Subject = 'Closed',
            taskList.add(t);
        }

        try{
           insert taskList; 
        } catch(DMLException e){
           jobApp.addError('Error message');
        }       
    }
  }  
}

Trigger:

trigger JobTrigger on Job__c (after insert, after update) {

if(Trigger.isAfter){
    if(Trigger.isInsert || Trigger.isUpdate){
        JobTriggerHelper.create(Trigger.new);
    }
  } 
}
  • 1
    You are not restricted on number of methods in an apex class. You can add as many as you can maintain. – Jayant Das Sep 11 '18 at 22:02
  • There's also no restriction on the type, you can have static and non-static, public and private, sub classes, overrides etc. – gNerb Sep 11 '18 at 22:24
1

Best Answer

I would recommend reading through this answer for more help on what you're trying to do.

Direct Answer

I think there is an issue in your code. As it stands the task will be created each time a closed case is edited which is not what you want.

Try:

public static void create(List<Job__c> jobList, Map<Id, Job__c> oldMap){
    List<Task> taskList = new List<Task>();

    for(Job__c job : jobList){ 
        if (
            job.Stage__c == 'Closed' &&
            oldMap.get(job.Id).Stage__c != 'Closed' // Add this
        ) {
            Task t = new Task(
                Subject = 'Closed'
            );

            taskList.add(t);
        }
    }

    try{
        insert taskList; 
    } catch(DMLException e){
        jobApp.addError('Error message');
    }
}

This will make sure the task is only created when the Job__c.Stage__c changes from not being closed, to being closed.

In your trigger:

if (Trigger.isAfter && Trigger.isUpdate) {
    helper.create(Trigger.new, Trigger.oldMap);
}
| improve this answer | |
  • And NullPointerException :) It's not just update, but also insert. – Монте Кристо Sep 12 '18 at 8:05
  • 1
    The fix is less than 1 line of code. I'm sure you can figure it out. – gNerb Sep 12 '18 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.