function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nish321Nish321 

Trigger to create a case comment when a case is inserted

Can anyone help me out with this trigger?  I would like to create a new case comment whenever a case is inserted or updated. Below is the trigger i've written:

trigger UpdateanotherObj on Case (after insert, after update) {

//whenever a case is created a student should also be created 
set <ID> Caseids =  new set<ID> ();
 list<casecomment> casecommentlist = new list <casecomment> ();
 // casecomment[] comments = new casecomment[0];
 // database.dmloptions option = new database.dmloptions();

for (case c : trigger.new)

{

caseids.add(c.id);

}

 // list<casecomment>  cc =    [select ID, ParentID from CaseComment where ParentID IN : caseids] ;
  
for(case c : trigger.new  )
{

casecomment cc = new casecomment();
 cc.parentid = c.ID;
cc.commentbody = 'case comment this is';
cc.ispublished = true;
casecommentlist.add(cc); 
}
  insert casecommentlist;

}
Abhishek Singh 88Abhishek Singh 88
try this.
list<casecomment>  cc =    [select ID, ParentID from CaseComment where ParentID IN : caseids] ;
For(case c:trigger.new)
{
     if(cc.parentid==c.id)
       cc.add(new casecomment.commentbody('case comment this is'));
}
insert cc;
 
Tavva Sai KrishnaTavva Sai Krishna
Hi ramshah,

Your trigger works well . what ever you written is correct. I have removed the unnessary code and comment lines. try with below code.
 
trigger UpdateanotherObj on Case (after insert) {

//whenever a case is created a student should also be created 

 list<casecomment> casecommentlist = new list <casecomment> ();


for(case c : trigger.new  )
{

casecomment cc = new casecomment();
 cc.parentid = c.ID;
cc.commentbody = 'case comment this is';
cc.ispublished = true;
casecommentlist.add(cc); 
}
 
insert casecommentlist ;

}
Regards,
Sai Krishna Tavva.
 
Mahesh DMahesh D
Hi Ramshah,

Please find the below modified trigger:
 
trigger CaseTriggerOne on Case (after insert, after update) {
    //whenever a case is created a student should also be created 
    List<CaseComment> ccList = new List<CaseComment>();
    
    for(Case c : trigger.new) {
        caseComment cc = new casecomment();
        cc.parentid = c.ID;
        cc.commentbody = 'Case comment this is';
        cc.ispublished = true;
        ccList.add(cc);
    }
    insert ccList;
}

Please do let me know if it helps you.

Regards,
Mahesh
Mahesh DMahesh D
Hi Ramshah,

Please make sure that you adding few more conditions in case of update scenario as it will always creates a Case Comments for every update.

I also modified the trigger to consider:
(1) Naming Convention.
(2) Alignment.
(3) Bulkified the trigger.
(4) I already tested the above code and it is working fine.

Please do let me know if it helps you.

Regards,
Mahesh