I have a requirement. Contact related to activity, I need to pull his functional role ( custom field) on Activity page layout. So whenever I create an activity and relate with ant contact so his/her functional role should populate automatic.
Please help! How can I achieve it? I tried formula field but unable to get. I tried through trigger but it is not updating the field.
trigger updatefunctionalrole on Event (before insert, before update) {
// Create a map between the contact ID and its functional role value
Map<ID,String> confunrole = new Map<ID,String>();
List<Event> conEvents = new List<Event>();
// Loop through the triggered Events and add all of the contact IDs (for those associated with conortunities)
for (Event e : trigger.new) {
// Only Events associated with contact
if (e.whoID!= null && ((String)e.whoID).startsWith('003 ')) {
// And only newly inserted events or those being reparented to an contact
if (trigger.isInsert || (trigger.isUpdate && e.WhoID != trigger.oldMap.get(e.id).WhoID)) {
confunrole.put(e.whoID,'');
conEvents.add(e);
}
}
}
// Query the contact and add their functional role to the map
for (contact con : [SELECT Functional_Role__c FROM contact WHERE ID IN :confunrole.keySet()]) {
confunrole.put(con.id,con.Functional_Role__c);
}
// Update the contact functional role field on the Event with the relevant value
for (Event e : conEvents) {
e.contact_functional role__c = confunrole.get(e.whoID);
}
}
Test class is
@isTest
private class updatefunctionalroleTest
{
static testmethod void testbatch1()
{
Account acc = new Account(Name='Test Account');
insert acc;
List<contact> cons = new List<contact>();
for (integer i=0; i<50; i++)
{
contact con = new contact();
con.AccountId=acc.Id;
con.First Name='My';
con.Last Name ='contact'+i;
con.Email='[email protected]';
con.Phone='+12345';
con.Functional_Role__c = 'Information';
con.Title = 'CEO';
con.Level__c = 'Director';
cons.add(con);
}
insert cons;
Event Evt = new Event();
Evt.whatId = acc.Id;
Evt.Subject = 'Testing';
Evt.ShowAs = 'Busy';
Evt.Location = 'UAE';
Evt.ActivityDate = System.today()+15;
insert Evt ;
Test.startTest();
updatefunctionalrole obj = new updatefunctionalrole ();
Database.executeBatch(obj, 200);
Test.stopTest();
}
}