James Derulo's

Portfolio

How to dynamically typecast an sObject to custom object in VisualForce and in Apex

Leave a Comment
Scenario :1 : In runtime, I have to typecast (convert object type) through Visualforce Pages 

I designed the code that handle pagination, which was handled through a base controller. Something like this 
 public abstract List<sObject> getCastedData();

Now the idea was, that every custom controller which implement the base controller, can write its own definition and return its own 'return type' 

So after designing Visualforce Page, I added a table where I inserted data in, as shown in code snippet here

Here is how the pageTable looks like 
  <apex:dataTable value="{!PagedData}"  var="c"   >
<apex:column >
<apex:facet name="header">PageData</apex:facet>
<apex:outputText value="{!c.Account__r.SomeValue__c]}" />
</apex:column>

First thing came to my mind was, use dynamic binding to dynamically type cast object if required, 
Now dynamic binding is way showing fields that are determined in run time, mostly useful in managed packages .So if I used dynamic binding than how will I use this
<apex:outputText value="{0, number, $###,###}">
<apex:param value="{!c.Amount__c}" />
</apex:outputText>
<apex:outputText value="{0,date,dd/MM/yyyy}">
<apex:param value="{!c.Date_Of_Birth__c}" />
</apex:outputText>

I always wonder if there a  direct way of typecasting in runtime  for Visualforce Pages. So one of the approach was to give child controller (which implement base-controller) a job of typecasting. Since I couldn't find anything 'clean' provided by Salesforce so here is the method helped me dynamically type casting from sObject to custom Object type

public List<Custom__c> getCastedData() {
List<Custom_c> customPagedData = new List<Custom__c>();
for(SObject record : getPagedData()) {
CustomPagedData.add((Custom__c) record));
}
return CustomPageData;
}

+Ralph - helped my question resolving this through Google Plus discusion which is was simplistic  approach of typecasting. I believe there must be some other method that you might know of, please advice if you know or have written down some recipe 

Scenario :2  Applied method 

While working with Dynamic SOQL. I was passing dynamic string and used Database.Query(dyanmicQuery) to return the result, which was a list of Account from other sObject Type.

String sql = 'select id, Name from Account limit 10';
List<Account> accList= Database.query(sql);


I learned the result came with an exception of Illegal assignment 'List<sObject> to List<Account> for some reason, and I re-used same method which helped me achieving my data
    String sql = 'select id, Name from Account limit 10';
   List<Account> accList = getCastedData(Database.Query(sql));
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment