Let's consider the below scenario:
I have a scenario to type cast sObjectList into the List<customObject__c> so that I can access customObject fields and store it into the following:
String customValue1 = '';
String customValue2 = '';
String customValue3 = '';
String customValue4 = '';
Based on the recordId I'm fetching the targetobjectApi
name and getting the fields to query on this object from the custom metadata created.
After constructing the SOQL - String soqlQuery = 'SELECT ' + fields + ' FROM ' + targetObjectApiName; // It returns the sobject List
Now in the switch case I have to write a logic to convert this sobject list returned into customObject__c
list so that I can access fields on the customObject__c
.
Please find the code below:
String recordId = 'a2r540000014DwFAAU';
//Create String to store the query
String query = '';
String fields = '';
//Create String to store custom Object values
String customValue1 = '';
String customValue2 = '';
String customValue3 = '';
String customValue4 = '';
//Create List to Store customObject__c
List<customObject__c> customObjectList = new List<customObject__c>();
Id newId = Id.valueOf(recordId);
String targetObjectApiName = newId.getSObjectType().getDescribe().getName();
System.debug('targetObjectApiName-------->' + targetObjectApiName);
//Get Fields From Custom Metadata
List<customMetadata__mdt> customMetadataRecords = [SELECT Field__c, Object__c FROM customMetadata__mdt WHERE Object__c = :targetObjectApiName];
System.debug('customMetadataRecords---------->' + customMetadataRecords);
if(customMetadataRecords!=null && !customMetadataRecords.isEmpty()){
for(customMetadata__mdt mdtObj: customMetadataRecords){
fields = mdtObj.Field__c;
System.debug('fields---------->' + fields);
}
}
//Construct SOQL Query
String soqlQuery = 'SELECT ' + fields + ' FROM ' + targetObjectApiName;
System.debug('soqlQuery----------->' + soqlQuery);
List<sObject> sObjectList = Database.query(soqlQuery);
System.debug('sObjectList--------> ' + sObjectList);
//Store Values
if(sObjectList!=null && !sObjectList.isEmpty()){
switch on targetObjectApiName {
when 'customObject__c' {
//Need help here in typecasting
customObjectList = (List<customObject__c>) sObjectList;
//Need help here in storing customField__c values
customValue1 = customObjectList[0].customField1__c;
customValue2 = customObjectList[0].customField2__c;
customValue3 = customObjectList[0].customField3__c;
customValue4 = customObjectList[0].customField4__c;
}
when else {
return 'Other Option';
}
}//End Switch
}
Any kind of help is appreciated. Thank you