0

I have a requirement where in lightning web components , I am using design attributes so that admin can enter the objectApiname and fieldApiname.In fieldApiname,admin can give direct fieldapiname of any object or relationshipname.fieldapiname(Eg:Contacts.ContactField1__c).In apex, I am dynamically forming query based on the object and fieldapiname given in design attributes and fetching records. The query can be a direct query

Select Id,AccountField1__c,AccountField2__c from Account where Id = '000xxxx';

Or it can be a relationship query - getting child records from parent

Select Id,AccountField1__c,AccountField2__c,(Select ContactField1__c,ContactField2__c from Contacts),(Select OppField1__c,OppField__c from Opportunities) from Account where Id = '000xxxx' 

Design attributes : Here object name and field name can be anything.

ObjectApiName : Account
Field1ApiName : AccountField1__c
Field2ApiName : AccountField2__c
Field3ApiName : Contacts.ContactField1__c [Relationshipname.fieldName]
Field4ApiName : Contacts.ContactField2__c
Field5ApiName : Opportunities.OppField1__c

Apex

      @auraEnabled(cacheable=true)
      public static void getFieldDetails(String objectApiName,List<String> fieldsList,String recordId)
{
/*fieldsList - Fields given by admin in design attributes */
    for(String field : fieldsList)
    {
    **** Forming final dynamic query****
    Eg:finalQuery = Select Id,AccountField1__c,AccountField2__c,(Select ContactField1__c,ContactField2__c from Contacts),(Select OppField1__c from Opportunities) from Account where Id = '000xxxx' 
    }
    
    recordsList = Database.query(finalQuery);
     for(sobject record : recordsList)
        {
        for(sobject childRecord : record.***)
        {
        
        }

        }
}

I am not getting idea of how to write the logic.Here number of for loops to get child records will be based on the child fields entered by admin in design attributes.There can be child fields or all fields can be from same object. And moreover when I use sobject in for loop, I am getting error as

Variable does not exist: Contacts

for this line

for(sobject childRecord : record.Contacts)

Here I hardcoded as Contacts, but it will be any childrelationship name If anyone has idea how to resolve it,please help me.

0

You should be able to use the .getSObjects method like this:

recordsList = Database.query(finalQuery);
for(sobject record : recordsList) {
    for(sobject childRecord : record.getSObjects('Contacts')) {
        system.debug(childRecord.get('ContactField1__c'));
    }
}

Can review the documentation here:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm

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.