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
Emo514Emo514 

Trying to use dynamic Apex to retrieve values from a custom object

I'm following the Apex example and have created a Line Item object. I am trying to get the names and values for each of the fields in the object. I've reduced the example to the following fields: Created By, Unit Price and Merchandise (name of the product sold)

 

I have tied a visual force page to a button that when clicked activates an Apex class.

<apex:page standardController="Line_Item__c" extensions="VFController" action="{!autoRun}">
  <apex:messages />
</apex:page>

 

 

In my Apex class I tried to use getRecord() on the controller but there was an exception "SObject row was retrieved via SOQL without querying the requested field:" whenever I called the get('unit_price__c') method for example.

 

So I dynamically created a query, but now the Created By and Merchandise values are what appear to be keys and not the actual values (A4223400034 instead of 'Wii Jet' for example. Does anyone know how to get the actual token values from an object? I see them on the page so I'm sure there is a way to get the actual token value and not the ID.

 

Expected: createdbyid|foo                      unit_price__c|20  merchandise__c|Wii Jet

Actual:       createdbyid|005U0Irv0IAC  unit_price__c|20  merchandise__c|a01U010x4KIAQ

 

Apex class code:

public class VFController {

    private final SObject s;
    private final String id;
   
    public VFController(ApexPages.StandardController stdController) {
        s = stdController.getRecord();
        id = stdController.getId();
    }
 
    // Code we will invoke on page load.
    public PageReference autoRun() {

        //get the object details
        Schema.Describesobjectresult details = s.getSObjectType().getDescribe();
        Map<String, Schema.SObjectField> fieldInfo = details.fields.getMap();

        //create the select statement
        String query = 'SELECT ';
        for(String name : fieldInfo.keySet()) {
            query += name + ', ';
        }
       
        //remove extra ,
        query = query.substring(0, query.length()-2);

        //query and output messages
        query += ' FROM ' + details.getName() + ' WHERE id=\'' + id + '\'';
        sObject dataFields = Database.query(query);

        ApexPages.Severity error = ApexPages.Severity.Error;
        for (String name : fieldInfo.keySet()){
            ApexPages.Message myMsg = new ApexPages.Message(error,' Field:' + name +
             '|' + String.valueOf(dataFields.get(name)));
            ApexPages.addMessage(myMsg);
        }
       
        return null;
    }
}

 

Alex.AcostaAlex.Acosta

Even though you're doing this dynamicly you'll need still need to query into your lookup relationship and get any information you need. IE: Owner looks up to user so you'll have to change your owner field within your query to look somethink like this:

 

Select a.Owner.Name From Account a

 

Keep in mind you're currently accessing data outside from what you are currently requesting within your query. You'll get the Id because that is the relationship to other objects, but you need to crawl down deeper within your query to get more data.

 

Please tick if this is the correct answer

Emo514Emo514

Do you know how I can programatically get the relation information?

 

From the DescribeFieldResult I'm able to get the RelationName and sObject reference. But they don't seem to point to anything that is usable.

 

For example: Field: CreatedById has RelationshipName 'CreatedBy' and sObject references  'User'

However there is no 'CreatedBy' child relation for my object.

 

So I can't do the SELECT (SELECT Name from CreatedBy) From Line_Item__c as the relation example from the documentation suggests.

 

But even if there were such a relation, there is no identifier to say what is a valid column in the User object; so in this case 'Name' is assumed to be a valid column, but that isn't always guaranteed.

Alex.AcostaAlex.Acosta

There are a few columns which will be always present such as Name, Id, Created Date, Created By, etc on at least all custom objects. There are a few standard objects which will not have these, as in EntitySubscription, etc.

 

You can get back all sObjects if you'd like to validate what fields they have. Take a look at http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_describe_objects_understanding.htm#apex_describe_object_access_all