Friday 6 September 2013

Dynamic List Of Fields On The Basis of There Data Types #Salesforce

Hey I am back again with something new I have tried.

Now what do we have here
1. Picklist of Objects.
2. Picklist of DataTypes.
3. A Table with a list of Fields and there type

When user will select an an Object from the first picklist and then the User need to select the DataType from the second picklist and hit the button "Get Fields", then just in below section Named "Results" will be populated with the fields having the data Type selected by the user.

Here is a screen shot

Here is the apex Class,
 /** Description : Fetch all the fields with a common data type of an object.  
 *  
 * Created By : Abhi Tripathi  
 *  
 * Created Date : 09/05/2013  
 *  
 * Version : V1.0  
 **/  
 public with sharing class FetchFieldOfObjectWithDataType {  
   //Map to hold the [object name-Field Data Type] as key and List of fields as value  
   Map> mapObjectNameDataTypeKeyWithFields;  
   //String to hold the object name selected   
   public String selectedObjectNameString { get; set;}  
   //String to hold the data type selected  
   public String selectedDataTyepString { get; set;}  
   //Select List for holding sObject Select list  
   public List options { get; set;}  
   //Boolean variable   
   public Boolean isSelected;   
   //Fields list   
   public List sObjectFieldsList {get; set;}  
   //List of wrapper class  
   public List listWrap { get; set; }  
   //Data Type options Select list  
   public List getOperations() {  
     //List to hold the Data type options picklist  
     List options = new List();  
     options.add(new SelectOption('','Select one'));   
     options.add(new SelectOption('TEXT','Auto Number'));   
     options.add(new SelectOption('BOOLEAN','Checkbox'));   
     options.add(new SelectOption('CURRENCY','Currency'));   
     options.add(new SelectOption('DATE','Date'));   
     options.add(new SelectOption('DATETIME','Date/Time'));   
     options.add(new SelectOption('EMAIL','Email'));  
     options.add(new SelectOption('STRING','Formula'));   
     options.add(new SelectOption('LOCATION','Geolocation'));   
     options.add(new SelectOption('REFERENCE','Lookup'));   
     options.add(new SelectOption('INTEGER','Number'));   
     options.add(new SelectOption('DOUBLE','Percent'));   
     options.add(new SelectOption('PHONE','Phone'));   
     options.add(new SelectOption('PICKLIST','Picklist'));   
     options.add(new SelectOption('MULTIPICKLIST','Picklist (Multi-Select)'));   
     options.add(new SelectOption('STRING','Text'));   
     options.add(new SelectOption('TEXTAREA','Text Area'));   
     options.add(new SelectOption('URL','URL'));   
     return options;   
   }  
   //Method to check the Sobject is selected or not  
   public void OnSelectAction(){  
     if(selectedObjectNameString != null && selectedObjectNameString != '' )   
       isSelected = true;  
     else   
       isSelected = false;  
   }  
   //Calling Constructor  
   public FetchFieldOfObjectWithDataType() {  
     //Memory allocation   
     mapObjectNameDataTypeKeyWithFields = new Map>();  
     options = new List();  
     sObjectFieldsList = new List();  
     options.add(new SelectOption('','Select one'));   
     //Loop through sObject list  
     for(Schema.SObjectType sobj : Schema.getGlobalDescribe().Values()) {  
       //Get described of object  
       Schema.DescribeSObjectResult f = sobj.getDescribe();  
       //Check if object is accessible or not  
       if(f.isAccessible() && f.isCreateable())  
         //Populate list with options  
         options.add(new SelectOption(f.getName(),f.getLabel()));   
     }   
     //Sorting the list alphabetially   
     options.sort();  
   }  
   //Method  
   public void getFieldType() {  
     //List to hold the fields string  
     List fieldNameStringList = new List();  
     mapObjectNameDataTypeKeyWithFields = new Map>();  
     listWrap = new List();   
     //Loop over sObject fields  
     for(Schema.Sobjectfield sObjectFields : Schema.getGlobalDescribe().get(selectedObjectNameString).getDescribe().fields.getMap().values()) {  
       //Get Described variable  
       Schema.Describefieldresult fieldDescribedResult = sObjectFields.getDescribe();  
       //Checking map for value corresponding to the key  
       if(mapObjectNameDataTypeKeyWithFields.containsKey(String.valueOf(fieldDescribedResult.getType())) == false) {  
         //List having label of fields  
         fieldNameStringList = new List{fieldDescribedResult.getName() + '-' + fieldDescribedResult.getLabel() + '-' + String.valueOf(fieldDescribedResult.getLength()) + '-' + String.valueOf(fieldDescribedResult.isAccessible()) + '-' + String.valueOf(fieldDescribedResult.isUpdateable())};  
           }   
       else {  
         fieldNameStringList = mapObjectNameDataTypeKeyWithFields.get(String.valueOf(fieldDescribedResult.getType()));  
         fieldNameStringList.add(fieldDescribedResult.getName() + '-' + fieldDescribedResult.getLabel() + '-' + String.valueOf(fieldDescribedResult.getLength()) + '-' + String.valueOf(fieldDescribedResult.isAccessible()) + '-' + String.valueOf(fieldDescribedResult.isUpdateable()));  
       }   
       //Populate map with the values   
       mapObjectNameDataTypeKeyWithFields.put(String.valueOf(fieldDescribedResult.getType()), fieldNameStringList);   
     }  
     //Get corresponding fields names  
     sObjectFieldsList = mapObjectNameDataTypeKeyWithFields.get(selectedDataTyepString);   
     //Integer variable   
     Integer i=1;  
     //Check for null   
     if(sObjectFieldsList != null) {  
       //loop through the value of the map  
       for(String str : mapObjectNameDataTypeKeyWithFields.get(selectedDataTyepString)) {  
         //add to wrapper  
         listWrap.add(new WrapperFields( i++ , str.split('-')[0] , str.split('-')[1] , str.split('-')[2] , str.split('-')[3] , str.split('-')[4]));   
       }  
     } else {  
       //Error message  
       ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Fields Are Not Available For This Data Type'));   
     }  
   }  
   //Wrapper Class to hold different type of values  
   public class WrapperFields {  
     //Variable   
     public Integer srNm { get; set; }  
     public String nameOfField {get ; set ; }  
     public String labelOfField {get ; set ; }  
     public String lengthOfField {get ; set ; }  
     public string updatable { get; set; }  
     public string accessable { get; set; }   
     //Calling Constructor  
     public WrapperFields(Integer srNm , String nameOfField , String labelOfField , String lengthOfField , string updatable , string accessable) {  
       this.srNm = srNm;  
       this.nameOfField = nameOfField;  
       this.labelOfField = labelOfField;  
       this.lengthOfField = lengthOfField;  
       this.updatable = updatable;  
       this.accessable = accessable;  
     }  
   }  
 }  

VisualForce Page
 <!--   
 /** Description  :  Fetch all the fields with a common data type of an object.  
  *  
  * Created By   :  Abhi Tripathi    
  *  
  * Created Date  :  09/05/2013  
  *  
  * Version    :  V1.0  
 **/  
 -->  
 <apex:page controller="FetchFieldOfObjectWithDataType" tabStyle="Lead">  
 <apex:sectionHeader subtitle="Describe Your sObject" />  
   <apex:form >   
   <apex:pageMessages />  
     <apex:pageBlock >  
       <apex:pageBlockButtons >  
         <apex:commandButton value="Get Fields" action="{!getFieldType}"/>  
       </apex:pageBlockButtons>  
       <apex:pageBlockSection title="Object And Data Type" columns="1" >  
         <br/>  
         <br/>   
         <!--objects-->  
         <apex:selectList required="true" value="{!selectedObjectNameString}" size="1" label="Select Object Name" >  
           <apex:selectOptions value="{!options}"/>  
           <apex:actionsupport event="onclick" rerender="pick" action="{!OnSelectAction}"/>   
         </apex:selectList>  
         <br/>  
         <br/>   
         <apex:selectList required="true" value="{!selectedDataTyepString}" size="1" label="Select Data Type" >  
           <apex:selectOptions value="{!Operations}"/>  
           <apex:actionsupport event="onclick" rerender="pick" action="{!OnSelectAction}"/>   
         </apex:selectList>    
       </apex:pageBlockSection>    
         <br/>   
         <br/>  
         <apex:pageBlockSection title="Results" columns="1" >  
           <apex:pageBlockTable value="{!listWrap}" var="item" rendered="{!(sObjectFieldsList.size != 0 || sObjectFieldsList = null)}">  
             <apex:column >  
               <apex:facet name="header">Sr. No.</apex:facet>  
                 {!item.srNm}  
             </apex:column>  
             <apex:column >  
               <apex:facet name="header">API Name</apex:facet>  
                 {!item.NameOfField}  
             </apex:column>  
             <apex:column >  
               <apex:facet name="header">Label</apex:facet>  
                 {!item.LabelOfField}  
             </apex:column>  
             <apex:column >  
               <apex:facet name="header">Length</apex:facet>  
                 {!item.LengthOfField}  
             </apex:column>  
             <apex:column >  
               <apex:facet name="header">Editable</apex:facet>  
                 {!item.updatable}  
             </apex:column>  
             <apex:column >  
               <apex:facet name="header">Accessable</apex:facet>  
                 {!item.accessable}  
             </apex:column>  
           </apex:pageBlockTable>   
           <!--displaying the records when there is no record to display-->       
           <apex:outputText rendered="{!(sObjectFieldsList.size = 0 || sObjectFieldsList = null)}" value="No record(s) to display" />  
       </apex:pageBlockSection>  
     </apex:pageBlock>   
   </apex:form>  
 </apex:page>  


19 comments:

  1. Must read post for beginners. Awesome...

    ReplyDelete
  2. through metadata api i created field but how to display created field dynamically in an visualforce page

    ReplyDelete
    Replies
    1. Hi Mahesh,
      It doesn't matter how you created a field in this code, it will fetch the field according to there Data Type from the particular object.

      Delete
    2. Thank you Abhi Tripathi,
      Actually i try to copy and paste but Map and List related types some problem.

      please help me......

      Delete
    3. Thank you Abhi Tripathi,
      Actually i try to copy and paste the above code but Map and List related types some problem.

      please help me......

      Delete
    4. Hi Mahesh,
      Give me your email id . i'll send you the code.

      Regards

      Delete
    5. Hi Abhi,

      Can you plz send the code to "susheelkumarbusireddy@gmail.com"

      Delete
  3. Hi,
    above code is possible to using wrapper class.Using wrapper class how to display Field LableName,Api Name and data type using visualforce page and apex class.

    please help me

    ReplyDelete
    Replies
    1. Hi Mahesh,

      Using wrapper class, you can create variable in wrapper class to hold the value of Labels, Api Names and Data Type. This response comes when we use schema methods like getDescribe() method.
      But I think that approach is not good for practice.
      Schema response is too easy to handle on the same class.

      Regards

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Hi Abhi Tripathi,
      the above code display (pageblocktable)looks like same, but without using picklist values.Only display Fields label name,api name and type related fields with in the pageblocktable using wrapper class .Please help me............

      Delete
    4. Sent you a mail.

      Thanks :)

      Delete
    5. Hi Abhi Tripathi,
      I complete above task,Now Actually ,In my requirement Object like following type
      string strtemp = ‘Mahesh__’+strFieldName + ‘__c’;//Object come as through URL like strFieldName(object name in the form of string).

      How to assign strtemp to object type?

      please help me………….

      Delete
    6. Hi Mahesh,
      You can use this list of Schema.Sobjectfield

      Schema.getGlobalDescribe().get(stringOfObjectName).getDescribe().fields.getMap().values();

      Delete
    7. This comment has been removed by the author.

      Delete
  4. Hi Abhi Tripathi,
    using this (Schema.getGlobalDescribe().get(strtrmp).getDescribe().fields.getMap().values();)i displayed all fields in an visualforce page related to this Object(String strtemp=‘Mahesh__’+strFieldName + ‘__c’;)
    .But I try to add edit and delete functionalities these object(strtemp) related fields.That's why gave like the following in Wrapper class.
    Public class Wrapper()
    {
    public strtemp obj{get; set;}//Here strtemp is like String strtemp = ‘Mahesh__’+strFieldName + ‘__c’;

    public Wrapper(strtemp obj)
    {
    this.strtemp=strtemp;
    }
    }

    is it possible.Here i got error:Invalid type: strtemp

    how to assign strtemp like object Here?

    please help me.......

    ReplyDelete
  5. Hi,
    How to retrieve custom objects created dates in a pageblocktable using schema methods in an visualforce page?

    help me..

    ReplyDelete
  6. Abhinav Sharma18 May 2015 at 03:44

    Creation of map,List and their memory allocation is not correct.
    Please Update the same :-)

    ReplyDelete