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 New learnerSFDC New learner 

How to pass Object Id dynamically

Hi All,

I am trying to get the object prefix of Parent objects from child object.
In Case, I have the lookup to Opportunity and 2 custom objects. Here In my scenario, I am trying to create 2 records if an email is sent out to the customer. So, If an email is sent related to Opportunity object, my custom object field need to populate only opportunity id. Similarly with other objects should populate the caseid and that objectid.
I have written my code something like this.
 for(Case cs : Trigger.New){
        
        if(cs.Email_Template__c != Null && cs.Email_Template__c != ''){
            
            e = new EmailNotifications();
            e.CaseId= cs.id;
            e.OpporunityId = cs.Opportunity__c;
            e.EngagementId = cs.Engagement_ID__c;
            e.SessionId = cs.Session_ID__c;
            EmailList.add(e);            
        } 
        
    }
        if(EmailList.size()>0){
            CaseHandler.sendEmail(EmailList,MapEmailTemplate);
        }
public static void sendEmail(List <EmailNotifications> EmailList ,Map <String , CaseEN__c > MapParentEmailTemplate){
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        List<Email_Notification__c> reminderNotification = new List<Email_Notification__c>();
        List<Email_Notification__c> updatereminderNotification = new List<Email_Notification__c>();
Map<Id, Id> map_Formfields = new Map<Id, Id>();
        
        for(EmailNotifications en:Emaillist){
           
            string myIdPrefix;
            myIdPrefix = String.valueOf(en.CaseId).substring(0,3);
            if(myIdPrefix == '006'){
            map_Formfields.put(en.CaseId,en.OpporunityId);
            }
            if(myIdPrefix == 'a00'){
                map_Formfields.put(en.CaseId,en.EngagementId);
            }
            if(myIdPrefix == 'a05'){
                map_Formfields.put(en.CaseId,en.SessionId);
            }
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'abc@abc.com'};
                system.debug('toAddresses' +toAddresses);
            mail.setToAddresses(toAddresses);
            mail.setSubject('Hi');
            system.debug('hi');
            mail.setSenderDisplayName('Hi');
            system.debug('xyz');
           
            String body = 'Dear ' + cas.ContactEmail + ', ';
            body += 'First mail';
            system.debug('body'+body);
            mail.setHtmlBody(body);
            mail.setWhatId(cas.Id);
            mails.add(mail);
           
            List<Messaging.SendEmailResult> list_mr =Messaging.sendEmail(mails);
             Integer i=0;
            for(Messaging.SendEmailResult ser : list_mr){
                if(ser.isSuccess()){
                    Messaging.SingleEmailMessage maill = mails[i];
                    Id caseId = maill.getwhatId();
                    system.debug('caseId'+caseId);
                    Id ObjId = map_Formfields.get(caseId);
                   ManageEmailNotification( etname , myIdPrefix , ObjId,caseId,Emaillist);
                }
            }
             public static void ManageEmailNotification(String EmailTemplateName , String ObjectType , String ObjectId , Id caseId,List <EmailNotifications> EmailList){
                   list<Email_Notification__c> notificationlist = new list<Email_Notification__c>();
                List<Email_Notification__c> reminderNotification = new List<Email_Notification__c>();
                List<Email_Notification__c> updatereminderNotification = new List<Email_Notification__c>();
                for(EmailNotifications en : EmailList){
                    if (ObjectType == '006') 
                {
                     en.OpporunityId = ObjectId;  
                } 
               if (ObjectType == 'a00') 
                {
                     en.EngagementId= ObjectId;  
                } 
                if (ObjectType == 'a05')
                {
                    system.debug('ObjectType'+ObjectType);
                    en.SessionId = ObjectId; 
                    system.debug('ObjectId'+ObjectId);
                   system.debug('ObjectId'+en.SessionId); 
                }
            /*After Sending the Scheduled Email , Details will be updated to  Email Notification Object*/ 
            Email_Notification__c em= new Email_Notification__c();
            if(en.ScheduledFlag == False){
                system.debug('scheduled flag'+en.ScheduledFlag);
                if(en.OpporunityId != null)
                             {
                                 em.opportunity__c = en.OpporunityId;
                             }
                             else if (en.SessionId != NUll){
                                 em.Session__c = en.SessionId;
                             }
                             else if (en.EngagementId != NULL){
                                 em.Engagement__c = en.EngagementId;
                             }
                em.Case__c = en.CaseId; 
                em.Status__c = 'Sent';
               
                em.Email_Template__c = en.EmailName;
                notificationlist.add(em);    
            }
            /*After Sending the Scheduled Email , Details will be updated to  Email Notification Object*/  
            system.debug('Scheduled Flag boolean'+en.ScheduledFlag);
            system.debug('EmailTemplateName'+en.EmailTemplateName);
            
            if(en.ScheduledFlag == True){
                system.debug('update ');
                Email_Notification__c updatelist = new Email_Notification__c();
                system.debug('opp id'+en.OpporunityId);
                system.debug('Email_Template__c :::'+ en.EmailName );
                
                updatelist = [select id,status__c,Sent_Date__c from Email_Notification__c where   Opportunity__c = :en.OpporunityId ];
               
                updatelist.Status__c = 'Sent';
                
                updatereminderNotification.add(updatelist);
                break;
                
            }
           
            /*Check if the any remainder emails need scheduled*/
            if(en.ParentEmail == em.Email_Template__c ){
                
                Email_Notification__c em1 = new Email_Notification__c();
                if(en.OpporunityId != null)
                             {
                                 em1.opportunity__c = en.OpporunityId;
                             }
                             else if (en.SessionId != NUll){
                                 em1.Session__c = en.SessionId;
                             }
                             else if (en.EngagementId != NULL){
                                 em1.Engagement__c = en.EngagementId;
                             }
                em1.Case__c = en.CaseId;
               
                em1.Status__c = 'Scheduled';
                system.debug('em1'+em1.Status__c);
               
                system.debug('em1'+em1.Scheduled_Date__c);
                em1.Email_Template__c = en.getParentname(en.ParentEmail).Name;
                system.debug('em1'+em1.Email_Template__c);
                
               
                reminderNotification.add(em1); 
                
                
            }
        }
        if(notificationlist.size()>0){
           
            insert notificationlist;
        }
        if(updatereminderNotification.size()>0){
           
            Update updatereminderNotification;
        }
        if(reminderNotification.size()>0){
           
            
            insert reminderNotification;
        }
    }

1) How to dynamically I pass the object Id for that particular case?
2) Is there any way I can pass the object name and get the Opportunity prefix or other custom objects?
3) How to avoid writing code multiple times?
4) How to pass id dynamically in Update query 
select id,status__c,Sent_Date__c from Email_Notification__c where   Opportunity__c = :en.OpporunityId

Please anyone help me on this?
Any help will be greatly appreciated.

Thanks,
Sirisha         
Shivdeep KumarShivdeep Kumar
Hi Sirisha,

As per your first point:
you can pass the object Id and get the detail by dynamic apex:-

Schema.SObjectType sobjectType = myId.getSObjectType();
String sobjectName = sobjectType.getDescribe().getName();

As per your second point:
Yes you can get all reference object by standard method as below:-
 
For getting All Parent objects:

for(Schema.SobjectField strFld: Account.SobjectType.getDescribe().fields.getMap().Values()){
if(strFld.getDescribe().getType() == Schema.DisplayType.REFERENCE){
system.debug(‘==parent object=’+strFld.getDescribe().getReferenceTo());
}
}

For getting All Child objects:

Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship cr: R.getChildRelationships()) {
system.debug(‘====child object===’+cr.getChildSObject());
}

*Change Account as per your requirement.

As per your Third point:
create a method and call that when same code use again.

As per your Fourth point:
you can try as below:
Schema.SObjectType sobjectType = myId.getSObjectType();
String sobjectName = sobjectType.getDescribe().getName();

SObject record = Database.query('Select Id, Name From ' + sobjectName + ' Where Id = :myId');

Please let me know if this helps.

Thanks
Shivdeep
SFDC New learnerSFDC New learner
Hi Shivdeep,

Thanks for the reply and  explaining the points.
Below is my code , I am putting in a map and trying to get the id .
1) Instead of keeping each id in a map, Is there any way we can get the id's dynamically .
if(en.OpporunityId != NULL){
                system.debug('oppid==='+en.OpporunityId);
            map_Formfields.put(en.CaseId,en.OpporunityId);
                }
            if(en.CustomObject1!= NULL){
                
                map_Formfields.put(en.CaseId , en.CustomObject1);
            }
            if(en.CustomObject2 != NULL){
                
                map_Formfields.put(en.CaseId , en.CustomObject2);
            }

2) Once the email sent is Success. I am getting these Id's after I send out the email using WhatID 
                  Id caseId = maill.getwhatId();
                   
                    caseIdlist.add(caseId);
                    Id ObjId = map_Formfields.get(caseId);
                    ObjectIdlist.add(ObjId);
                    String etname = mapEmailName.get(caseId).EmailName;
                    etlist.add(etname);
                    ManageEmailNotification( etlist , ObjectIdlist , caseIdlist , Emaillist);
 But I am getting Invalid Id error near this method.
Can you pls help me?

Thanks,
Sirisha