Apex Tip: get relation field value on Dynamic SOQL

I’m used to work on dynamic Apex/SQOL. I think that is always a better use this good feature of Salesforce during the development step in order to reuse the code to many SObjects as possible.

You have to understand in deep the SObject class in Apex to maximise this technique. Once you work with SObject instead of the Object (Account for instance). You are able to reuse your method/code.

The basic is quite simple, you have an SObject and you can write a field value using o.put(‘fieldName’,’value’), and read a field value using o.get(‘fieldName’).

So, you can use Database.query() method in order to get a SObject list and apply your dynamic method.

However, I’ve faced a common issue when I tried to access to a field value which came from relation field.

For example if you try to get the values from this query:

You would get this error:

My solution was to implement a recursive helper method:

 

Happy code ;)

6 thoughts on “Apex Tip: get relation field value on Dynamic SOQL

  1. Igor Umansky

    I am trying to implement …

    String sSelect = ‘Select ‘ + sSelectColumns + ‘ From ‘ + sSysObject + ‘ ORDER BY ‘ + sSortColumns + ‘ Limit 10′;

    List sobjList = Database.query(sSelect);

    for(sObject sRow : sobjList)
    {
    String s1 = String.valueOf(sRow.get(‘Contact__c’)); // I see Con Id

    //String s2 = String.valueOf(sRow.get(‘Contact__r.Name’)); // I got error on relation value

    String s2 = sys_Helper.getFieldValue(sRow,’Contact__r.Name’);
    //Compile Error: Illegal assignment from Object to String at line 156 column 13
    }

    Reply
  2. Igor Umansky

    It’s working .. thanks, Martin!

    String sSelect = ‘Select ‘ + sSelectColumns + ‘ From ‘ + sSysObject + ‘ ORDER BY ‘ + sSortColumns + ‘ Limit 10′;

    List sobjList = Database.query(sSelect);

    for(sObject sRow : sobjList)
    {
    String s1 = String.valueOf(sRow.get(‘Contact__c’)); // Show Con ID
    Apexpages.addMessage(new Apexpages.Message(Apexpages.severity.INFO, ‘s1: ‘ + s1));

    //String s2 = String.valueOf(sRow.get(‘Contact__r.Name’)); // Getting Error on incorrect relation
    //Apexpages.addMessage(new Apexpages.Message(Apexpages.severity.INFO, ‘s2: ‘ + s2));

    Object obj = sys_Helper.getFieldValue(sRow,’Contact__r.Name’); // Show Con Name
    Apexpages.addMessage(new Apexpages.Message(Apexpages.severity.INFO, ‘obj: ‘ + obj));

    // DIY script :)
    }

    Reply

Leave a Reply to murali Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">