+ Start a Discussion
Itayb34Itayb34 

New Case to Create Case Comment Trigger

Hello

 

I've created a trigger to create a case comment whenever a new case is created (either manually or via the Self-Service Portal).

Comment is created from the case description

 

trigger TaskSubTrigger on Case (after insert) {

List<CaseComment> NewComment = new List<CaseComment>();
    
    for(Case ca: Trigger.new){
        
        CaseComment com = new CaseComment();
        com.ParentId = ca.id;
        com.CommentBody= ca.Description;
        NewComment.add(com) ;

                            }

Insert NewComment;

}

 1. Will it fail on bulk import?

 2. When I create case manually with description field empty, a case comment is created empty...any way to avoid this??

 

Thanks in advance!

 

Itay

Best Answer chosen by Admin (Salesforce Developers) 
RoyGiladRoyGilad

1. No, it will not fail, why did you think that? Am I missing something?

2. You can add "If" statement , it should solve the problem:

for(Case ca: Trigger.new){
        
        if (ca.Description !=null && ca.Description!='')
{
CaseComment com = new CaseComment(); com.ParentId = ca.id; com.CommentBody= ca.Description; NewComment.add(com) ; } }

 

 

Roy Gilad

All Answers

RoyGiladRoyGilad

1. No, it will not fail, why did you think that? Am I missing something?

2. You can add "If" statement , it should solve the problem:

for(Case ca: Trigger.new){
        
        if (ca.Description !=null && ca.Description!='')
{
CaseComment com = new CaseComment(); com.ParentId = ca.id; com.CommentBody= ca.Description; NewComment.add(com) ; } }

 

 

Roy Gilad

This was selected as the best answer
AdrianCCAdrianCC

1. nope... it seems to be bulk proof(you're using that List to make the insert). You can also test a bulk import with a test case method in your test class using a large list of Cases. Use a for loop to create the test records.

2. well that's exactly what your code does, isn't it? I'm refering to the 

com.CommentBody= ca.Description;

line. You could add an IF statement to give it a default value based on the ca.Description == null condition...

 

 

 

Thanks,

Adrian

Itayb34Itayb34

Roy, I've seen too many movies:)  in the majority of cases, the cases will be created one by one. For the scenario of bulk import, i'll verify by test class.

regarding 2, this is the exact piece that I forgot, much appreciated! 

parepalli.harikaparepalli.harika

Thank you so much..I have similar reuirement..auto case comment on new case created with particular account..