[SalesForce] Apex Trigger : Insert record on another object on “afterInsert” event

A fresher question.

We have a custom object named "CaseLogger".

CaseLogger does not have any custom fields.

Whenever a new Case is created, a CaseLogger record will be created with it's "Name" field being a concatenation of "Case Id + Case Origin".

For example let's think of a scenario in which Case C is created. Its Origin is "Email" and its Id is "19191".

Then a new CaseLogger record will be created as follows

CaseLogger.Name = 19191Email

I wrote the following trigger.

trigger CaseTrigger on Case ( after insert)
{

    List<CaseLogger__c> l = null;

    for(Case c : Trigger.new)
    {
        //I am stuck here 
    }

    insert l;       
}

I know the code that I wrote is not much.

  1. I know that we always have to "bulkify" and should use DML wisely.

  2. So If 1 is to be honored, then I assume that Case records present in Trigger.new are to be stored in a collection.

  3. But I am unable to find a method in List class that can allow me to create CaseLogger list entries with only data given for one of its fields

For example something like

l (the collection from the above code snippet)

l.Name.add(c.id+c.Origin)

Can someone help ?

Best Answer

There are a couple of things wrong with your above snippet and example, but they are easy to fix.

First you need to initialise your List.

List<CaseLogger__c> l = new List<CaseLogger__c>();

The add() method on a List<CaseLogger__c> will take a CaseLogger__c as its parameter:

l.add(new CaseLogger__c(Name = c.Id + c.Origin));

I'd also advise that you give l a more descriptive name.

Putting that all together you get:

trigger CaseTrigger on Case ( after insert)
{
    List<CaseLogger__c> loggers = new List<CaseLogger__c>();

    for(Case c : Trigger.new)
    {
        loggers.add(new CaseLogger__c(Name = c.Id + c.Origin));
    }

    insert loggers;
}
Related Topic