+ Start a Discussion
KaityKaity 

Trigger

When we write trigger on event after insert and after update event to update field on different object, then should we always the DML operator at the last like:

 

insert myList;

update myList;

 

Can some one give an example?

Best Answer chosen by Admin (Salesforce Developers) 
souvik9086souvik9086

Yes for after insert and after update you have to use the DML operator for all objects.

For before event you dont have to use that for same object but have to use that DML for different objects.

 

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.

Thanks

 

 

All Answers

souvik9086souvik9086

Yes for after insert and after update you have to use the DML operator for all objects.

For before event you dont have to use that for same object but have to use that DML for different objects.

 

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.

Thanks

 

 

This was selected as the best answer
Venkatesh.ax1803Venkatesh.ax1803

Yes, u need to perform dml operations on other objects , below example shows

 

Here trigger on Position__c, and  trigger events are after insert, after update

If position is opened , we are creating one feedItem and u can see dml insertion on Feed Item with position id and groupuser id

 

trigger PositionAnnouncementTrigger on Position__c (after insert, after update) {
    
    List<CollaborationGroup> allUserGroup = [SELECT id FROM CollaborationGroup WHERE name='All Universal Containers' LIMIT 1];
    List<FeedItem> itemsToPost = new List<FeedItem> ();
    for (Position__c position: Trigger.new) {
        if ((Trigger.isInsert
             || position.status__c!= Trigger.oldMap.get(position.id).status__c
               || position.sub_status__c!=Trigger.oldMap.get(position.id).sub_status__c)
                    && position.status__c =='Open' && position.sub_status__c =='Approved') {
                
                itemsToPost.add(new FeedItem(parentId=allUserGroup[0].id,
                     body='Recommend someone for this position '
                     + position.Name, linkURL='/' + position.id));
            }                             
    }
    if (itemsToPost.size() > 0) {
        Database.insert(itemsToPost); //DML Insertion
    }
}