+ Start a Discussion

How to cast objects in a VF page?

Hi ,


In our project we have many tables where we are required to display checkboxes and the associated records. So we have used  an equal number of wrapper classes for each object. I was planning to generalize it, by soing something like this(below code), but was unsuccessful. I am not sure how to cast an generic sObject back to a specific object in a VF page


//apex Class:

public class genericObjectCreation{
    public class wrapperClass{
        //using a generic sObject.
        public sObject acc {get;set;}
        public boolean x {get;set;}
        public wrapperClass(sObject a){
            this.acc = a;
   public list<wrapperClass> wrapperList{get;set;}
   public genericObjectCreation(){
       wrapperList = new list<wrapperClass>();
       for(account a : [select name from account]){
            wrapperList.add(new wrapperClass(a));

//VF Page:
<apex:page controller="genericObjectCreation">
            <apex:pageBlockTable value="{!wrapperList}" var="wp">
                <apex:column headerValue="boolean">
                    <apex:inputCheckbox value="{!wp.x}"/>
                <apex:column value="{!wp.acc.name}"/>            

When I open the VF page I get an error stating:
ERROR: Unknown property 'SObject.name'
Error is in expression '{!wp.acc.name}' in component <apex:page> in page genericexample

 The error makes sense coz I am not casting the generic sObject back to account, the VF page is unable to get the value of .name. Any ideas how to go about it?





Chaten Raghav 9Chaten Raghav 9

Please check the following help link which has the correct and detailed information about the object binding on Vf pages.

Please check :- https://www.salesforce.com/us/developer/docs/pages/Content/pages_dynamic_vf_field_sets.htm

Basically, in your VF page, you are not able to get the name because you have used the bind values as "" {!wp.acc.name} "", however it should be used like :- {!wp.name} as you have already created a variable for ""wrapperList"" as ""wp"" and you can use that to cast the fields.

I hope this helps. Please mark it as ""Best Answer"" if it helps you.

Chaten Raghav