I'm trying to get the name of whatId and WhoId on the event object onto a string. I can do it for a single record inside a for loop, the issue I see when Im looking to bulkify the code is that events can be related to multiple objects and I need to query this dynamically while keeping a reference to the original record. my current code snippet for a single record is below

       for(event e : eventList){
       //get the name of the objects
        String whatIdsObjectType = e.whatId.getSObjectType().getDescribe().getName();
        String whoIdsObjectType  = e.whoId.getSObjectType().getDescribe().getName();

        //assign variables to the ids 
        id accId = e.whatId;
        id pcID  = e.whoId;  

        //query the name fields dymanically        
        string whatQueryString = 'Select Name FROM '+whatIdsObjectType+' WHERE id =:accId';
        string whoQueryString  = 'select Name FROM '+whoIdsObjectType+' WHERE id =:pcID';
        List<sObject> relatedToName = Database.query(whatQueryString);
        List<sObject> primaryContactName = Database.query(whoQueryString);

        //set values for the text fields on before update,before insert
        e.related_to_name__c = string.valueOf(relatedToName[0].get('Name'));
        e.primary_contact_name__c = string.valueOf(primaryContactName[0].get('Name'));


If all you want is the name, can't you just query What.Name and Who.Name from said Event object?

  • 1
    you are right..i got mislead by trying to create a formula field first and not being able to drill down to the what or who lookup! thanks for the help – JPG Sep 27 '18 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.