Saturday, 5 May 2012

Displaying fields of selected object from picklist using dynamic apex

Here we are displaying the fields of selected object in pageblocktable if it is not creatable otherwise it navigates to its insert page.

Controller for this:
==============
public class fieldNamescls{

    public PageReference fields() {
         Schema.SObjectType gd;
          Schema.DescribeSobjectResult a11;
          if(objectname!=null){
              gd = Schema.getGlobalDescribe().get(objectName);
              a11=gd.getDescribe();
        }
        pagereference pg;
        if(a11.isCreateable() && a11.isAccessible() && a11.isDeprecatedAndHidden()==false &&   a11.isQueryable() && a11.isSearchable())
                 pg=new Pagereference('/'+a11.getKeyPrefix()+'/e?');
                 return pg;
    }

public account acc{get;set;}
public string objectname{get;set;}
public string ren{get;set;}
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

public  List<selectOption> getvaluess(){
    List<selectoption> options=new List<selectoption>();
    for(string s:gd.keyset()){
        options.add(new selectoption(s,s));
          
    }
    return options;
}

public List<Schema.SObjectField> getFields(){
List<Schema.SObjectField> sss=new list<Schema.SObjectField>();
   if(objectname!=null){
           Schema.SObjectType gd = Schema.getGlobalDescribe().get(objectName);
           Schema.DescribeSobjectResult a11=gd.getDescribe();
           System.debug('all fields'+a11);
           Map<String, Schema.SObjectField> M = a11.fields.getMap();
          for(Schema.SObjectField s1:m.values()){
                        system.debug('----'+s1+'\n');
                        sss.add(s1);
       }
}
    return sss;
   
}

}
Visulaforce page code:
=============================
<apex:page controller="fieldNamescls">
  <apex:form >
  <apex:actionFunction action="{!fields}" name="fun"/>
      <apex:pageBlock >
     
          <apex:selectList value="{!objectname}" multiselect="false" size="1" onchange="fun()">
                  <apex:selectoptions value="{!valuess}"></apex:selectoptions>
          </apex:selectList>
       
          <apex:pageBlocktable value="{!Fields}" var="f" rendered="{!ren}">
              <apex:column headerValue="{!objectName}:Field Names" value="{!f}"/>
          </apex:pageBlocktable>
      </apex:pageBlock>
  </apex:form>
</apex:page>

=======================
Screen shot
====================

No comments:

Post a Comment