SOQL query object fields Salesforce Schema


public with sharing class FetchObjectData {
    public static Map<String, Object> getObjectFieldValues(Id objectAId) {
        // Map to store 'Object.field' => 'field.value'
        Map<String, Object> resultMap = new Map<String, Object>();

        // Describe Object A fields
        Schema.DescribeSObjectResult objADescribe = ObjectA__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> objAFields = objADescribe.fields.getMap();

        // Build a dynamic query for Object A
        String queryA = 'SELECT Id';
        for (String fieldName : objAFields.keySet()) {
            queryA += ', ' + fieldName;
        }
        queryA += ' FROM ObjectA__c WHERE Id = :objectAId';

        // Query Object A
        ObjectA__c objA = Database.query(queryA);

        // Populate fields of Object A
        for (String fieldName : objAFields.keySet()) {
            String key = 'ObjectA__c.' + fieldName;
            Object value = objA.get(fieldName);
            resultMap.put(key, value);
        }

        // Describe Object B fields
        Schema.DescribeSObjectResult objBDescribe = ObjectB__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> objBFields = objBDescribe.fields.getMap();

        // Query related Object B records
        String queryB = 'SELECT Id';
        for (String fieldName : objBFields.keySet()) {
            queryB += ', ' + fieldName;
        }
        queryB += ' FROM ObjectB__c WHERE LookupField__c = :objectAId'; // Replace LookupField__c with the correct lookup field name

        List<ObjectB__c> objBRecords = Database.query(queryB);

        // Populate fields of related Object B records
        for (ObjectB__c objB : objBRecords) {
            for (String fieldName : objBFields.keySet()) {
                String key = 'ObjectB__c.' + fieldName;
                Object value = objB.get(fieldName);
                resultMap.put(key, value);
            }
        }

        return resultMap;
    }
}
SOQL query object fields Salesforce Schema SOQL query object fields Salesforce Schema Reviewed by dasfrogpractice on 02:18 Rating: 5

No comments:

Theme images by mariusFM77. Powered by Blogger.
Youtube Channel Image
Dasfrog Subscribe To watch more Salesforce Training
Subscribe