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);
    }
  } 
}
2
  • 1
    You are not restricted on number of methods in an apex class. You can add as many as you can maintain.
    – Jayant Das
    Commented Sep 11, 2018 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
    Commented Sep 11, 2018 at 22:24

1 Answer 1

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);
}
2
  • And NullPointerException :) It's not just update, but also insert. Commented Sep 12, 2018 at 8:05
  • 1
    The fix is less than 1 line of code. I'm sure you can figure it out.
    – gNerb
    Commented Sep 12, 2018 at 14:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .