Skip to main content
Hello,

I am simply trying to access a few Case fields of a Case that has been created after an Apex trigger. However, I keep getting this error: "Invalid loop variable type expected SObject was Case". I am not sure what the problem is, as other sources online that I have looked at seem to be using the same syntax/declarations that I am using. As a sidenote, I am fairly new to Apex and am still learning as I go. Please bear with me.

Here is my code:

trigger Ticket_Trigger on Case (after insert) {

    List<Id> listId = new List<Id>();

    for(Case c : Trigger.new){

        listId.add(c.Id);

    }

    

    List<Case> caseList = [SELECT Case.Id, Case.Origin, Case.ContactId, Case.AccountId, Case.Status,

                           Case.Priority, Case.Subject, Case.LastModifiedById, Case.OwnerId,

                           Case.CreatedById, Case.CreatedDate, Case.Description 

                           FROM Case 

                           WHERE Case.id IN :setId];

    

    System.debug(caseList);

}
2 个回答
  1. 2019年6月10日 14:29
    Hi Fayyad,

    Follow these steps:

    1. Try to separate trigger and it's handler class.

    2. Always try to put the null check condition in your code.

    3. Never put query inside for loop.

    4. In your code, inside query use listId instead of setId.

    5. While you are store Id of any record use Set<Id>.

    6. In your code when the case list comes in the "trigger.new" why you are query this?

    Try this Code:

    Trigger:

    trigger Ticket_Trigger on Case (after insert) {

    if(trigger.IsInsert && trigger.IsAfter) {

    Ticket_Trigger_handler.showCase(trigger.new);

    }

    }

    Handler:

    public class Ticket_Trigger_handler {

    public static void showCase(List<Case> caseList) {

    try

    {

    Set<Id> caseIdSet = new Set<Id>();

    List<Case> caList = new List<Case>();

    if(caseList.size() > 0) {

    for(Case c : caseList)

    {

    caseIdSet.add(c.Id);

    }

    }

    caList = [SELECT Case.Id, Case.Origin, Case.ContactId, Case.AccountId, Case.Status,

    Case.Priority, Case.Subject, Case.LastModifiedById, Case.OwnerId,

    Case.CreatedById, Case.CreatedDate, Case.Description

    FROM Case

    WHERE Case.Id IN : caseIdSet];

    System.debug(caseList);

    }

    catch(Exception e)

    {

    system.debug('The following exception has occured:' +e.getMessage());

    system.debug('The following Line:' + e.getLineNumber());

    }

    }

    }

    I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

    Thanks,

    Ajay Dubedi
0/9000