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
sfdc.dev.ax856sfdc.dev.ax856 

Recent record from related list

Hi,

          I need to write a trigger to  get most recent record from related list "CampaignMember"  and update to it a custom field on parent "Contact".Any Idea?

Thanks

Ankit AroraAnkit Arora

Two things comes in my mind when you say "most recent"

 

1) Most recently updated/created

2) Most recently viewed.

 

If you are looking for the second point then I don't think this is possible with apex and if you are looking for the first point then you can just query on "CmapaignMember" with limit 5/10 (which ever suits you) and DESC on lastModified Date.

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

sfdc.dev.ax856sfdc.dev.ax856

Thanks Ankit for your reply.I need to get most recent created Campaign Member record from the related list of Contact and update the Campaign name to  a field on Contact.Can you please post the trigger syntax.

 

 

Ankit AroraAnkit Arora

Here is the logic which will help you to move ahead with the trigger code.

 

List<CampaignMember> camLst = [Select Status, LeadId, Id, CreatedDate, ContactId, CampaignId From CampaignMember ORDER BY CreatedDate DESC Limit 5] ;
List<Campaign> toUpdate = new List<Campaign>() ;
for(CampaignMember cm : camLst)
{
       Campaign camp = new Campaign(id = cm.CampaignId) ;
       camp.Name = cm.Contact.Name ;
       toUpdate.add(camp) ;
}

update toUpdate ;

 

You can change "cm.Contact.Name" to the field name which you want to fill in Campaign Name.

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

sforcegarrett7sforcegarrett7

Ankit,

 

This is really helpful.  I saved the trigger with the following code: 

 

trigger RecentCampaign on Contact ( after insert, after update, after undelete ) 
{
List<CampaignMember> camLst = [Select Status, LeadId, Id, CreatedDate, ContactId, CampaignId From CampaignMember ORDER BY CreatedDate DESC Limit 5] ;
List<Campaign> toUpdate = new List<Campaign>() ;
for(CampaignMember cm : camLst)
{
       Campaign camp = new Campaign(id = cm.CampaignId) ;
       camp.Name = cm.Contact.Name ;
       toUpdate.add(camp) ;
}

update toUpdate ;
System.debug( 'End of the Trigger?!');

}

 I am wondering why this code is compiling when I don't have a Contact.Name custom field on my Contact object?  Isn't the point to display the most recent Campaign Name in a custom field on the Contact record a user is viewing?

 

Also...don't you need a test class to support the trigger?