Tuesday, May 26, 2015

Schema.DescribeSObjectResult in Apex and its usage in visualforce.

Schema.DescribeSObjectResult in Apex and its usage in visualforce.


This Describes SObject methods returns an array of DecribeSobjectResult objects. Where each object has the following properties.

String Name : This is the name of the object.

String Label :  Label text for the tab or an objct.

String LabelPlural : Label text for an object that represents plural version of object name.

String keyPrefix :  Object id's are prefixed with 3 character quotes that specify the type of the object.

Ex: - Account obj as 001, Opportunity object has 006.

When we call the keyPrefix it will return 3 character prefix code for the object which we are called.


Field[] fields: This will return array of the fields associated with an object.

Boolean Custom: Indicated whether the object is a custom object or not.

Boolean Creatable: Indicates whether the object can be created via created method.

Boolean deletable: Indicates whether the object can be deleted or not.

Boolean Mergable: Indicates whether the object can be merged with objects of its type.

Replicatable: Indicates whether the object can be replicatable via getUpdate function or getDeleted.

Boolean Retrievable : Indicates whether the object can be retrieved using retrieve method or not.

Boolean Searchable:- Indicates whether object can be searched via Search method .


Boolean updatable : Checks whether the object can be updatable or not.

To fetch the properties of an object

Schema.DescribeSobjectResult resultObj = Account.SobjectType.getDescribe();

                                              Or
Schema.DescribeSobjectResult result =  Schema.SobjectType.Account();

Example:

Field Example:

 Public class FieldExample{

   public String result {get;set;}

  Public FieldExample() {

 Schema.DescribeSobjectResult resultObj =          Account.SobjectType.getDescribe();
 result = ' ' +resultObj ;

}

}

In the above program 'resultObj' cibtaubs description about the object Account. If you want to know the properties individually we can use.

String getLabel();
String getKeyPrefix();
String getLabelPlural(); etc...



Child Relationship methods for given Object:


List <Schema.ChilRelationship> getChildRelationShips(); 

If an sobject is a parent object we can access the child relationships as well as the child objects using ChildRelationShip object.  This method returns the list of child objects for the given Sobject.


List of Child Records:

Program to display the List of Child objects for a given object

EX:-
public class ChildRelationshipExample {

public List<SelectOption> options;

public List<SelectOption> getOptions(){
 return options;
}

public ChildRelationshipExample(){

options = new List<SelectOption>();
Schema.DescribeSobjectResult r = Account.SobjectType.getDescribe();
List<Schema.childRelationship> c = r.getChildRelationShips();

for(schema.childRelationship x:c){
 String name = ' '+x.getChildSObject();
 SelectOption op = new SelectOption(name,name);
 options.add(op);
}

}


}

VF Page:

<apex:page controller="ChildRelationshipExample">
  <apex:form >
   <apex:selectlist size="1">
     <apex:selectoptions value="{!options}"></apex:selectoptions>
   </apex:selectlist>
  </apex:form>
</apex:page>




  


RecordType info:


List<Schema.RecordTypeInfo>.getRecordTypeInfos();

This returns a list of record types created on this object. User may or may not have access to see this record type information.

Example to display the list of record types for a given object:



Ex:
Class:

public class RecordTypeInfoExample {

 public List<SelectOption> options;

 public List<SelectOption> getOptions(){
  return options;
 }

 public RecordTypeInfoExample(){
  options = new List<SelectOption>();
  String myObject = 'Opportunity';
  Schema.DescribeSobjectResult dsr = Opportunity.SobjectType.getDescribe();
  List<Schema.RecordTypeInfo> rt =dsr.getRecordTypeInfos();
  for(Schema.RecordTypeInfo inf: rt){
  
  SelectOption op = new SelectOption(inf.getName(),inf.getName());
   options.add(op);
  }
  

 }

}


Vf page:

<apex:page controller="RecordTypeInfoExample" >
 <apex:form >
   <apex:selectlist size="1">
     <apex:selectoptions value="{!options}"></apex:selectoptions>
   </apex:selectlist>
  </apex:form>
  

</apex:page>






RecordTypeInfoByID : -

Map<Id, Schema.RecordTypeInfo>.getRecordTypeInfoByID();

Returns the Map, matches the records id's of an object to their associated record types.

Program to display id's of recordtypes of a given object:

Ex:

public class RecordTypeInfoByIDExample {

    public List<Selectoption> options = new List<SelectOption>();
    public RecordTypeInfoByIDExample(){
        Schema.DescribeSObjectResult dsr = schema.SObjectType.opportunity;
        Map<Id,Schema.RecordTypeInfo> rtinfoMap = dsr.getRecordTypeInfosByID();
        Set<Id> s = rtinfoMap.keySet();
        
        for(id i: s){
            SelectOption op = new SelectOption(i,i);
            options.add(op);
        } 
        system.debug('options==>'+options);
    }
   
}



DescribeFieldResult:-

DescribeFieldResult stores the description about the field of an object, to get the description.

Schema.DescribeFieldResult obj = Account.Name.getDescribe();
                                                        Object Name , Field Name

DescriveFieldResult Methods:

String getLabel();
Integer getLength();
String getLocalName();
String getName();
Integer precission();
Integer getScale();
Boolean isAccessable();
Bollean isAutoNumber();
Boolean isCalculates();
Boolean isCustom();
Boolean isDependentPickList();
Boolean isIdLookup();
Boolean isRestrictedDelete();

Program to display the pickList values.

Ex:

public class DescribeFieldsExample {

public List<SelectOption> options;

public List<SelectOption> getOptions(){
 return options;
}

public String result {get;set;}

public DescribeFieldsExample (){
 options =  new List<SelectOption>();
 Schema.DescribeFieldResult obj = Account.Industry.getDescribe();
 List<Schema.pickListEntry> p = obj.getPickListValues();
 for(Schema.PickListEntry x:p){
  SelectOption op = new SelectOption(x.getLabel(),x.getLabel());
  options.add(op);
 }

}

}


VF Page:

<apex:page controller="DescribeFieldsExample" >
  <apex:form >
   <apex:selectList size="1">
    <apex:selectOptions value="{!options}"> </apex:selectOptions>
   </apex:selectList>
  
  </apex:form>
</apex:page>




                   


Write a program to display the list of all the fields of an object:

Map<String, Schema.SobjectField> M = Schema.SObjectType.Account.fields.getMap();

It is going to get all the fieldNames along with Properties.

Class:

public class FieldNamesExample {

public List<SelectOption> options;

public List<SelectOption> getOptions(){
 return options;
}

public FieldNamesExample (){
options = new List<SelectOption>();
 Map<String, Schema.SobjectField> M = Schema.SObjectType.Account.fields.getMap();
 system.debug('M==>'+M);
 Set<String> keys = M.keySet();
 for(String s : keys){
  SelectOption op = new SelectOption(s,s);
  options.add(op);
 }

}

}

Vf Page:

<apex:page controller="FieldNamesExample">
  <apex:form >
   <apex:selectList size="1">
    <apex:selectoptions value="{!options}"> </apex:selectoptions>
   
   </apex:selectList>
  
  </apex:form>
</apex:page>





Write a Program to display list of Custom Objects available in the organization and once the user select any object it has to display the list of fields of the corresponding object


Class:

public class ObjectFieldsExampleVF {

 Map<String,Schema.SobjectType> my;
 public String objName{get;set;}


 public List<SelectOption> myOptions;
 public List<SelectOption> options;

 public ObjectFieldsExampleVF(){
 options =  new List<SelectOption>();
 myOptions = new List<SelectOption>();
 my = schema.getGlobalDescribe();
 Set<String> myObj = my.keySet();
 for(String s:myObj){
  if(my.get(s).getDescribe().isCustom()){
   SelectOption ob = new SelectOption(s,s);
   myOptions.add(ob);
   

 }
 }
 }

 public PageReference show(){
 Map<String, Schema.SObjectField> fieldMap = my.get(objName).getDescribe().Fields.getMap();
 Set<String> keys = fieldMap .keySet();
 for(String s : keys){
  SelectOption op = new SelectOption(s,s);
  options.add(op);
 }
 return null;
 }

 public List<SelectOption> getOptions(){
  return options;
 }

 public List<SelectOption> getMyOptions(){
  return myOptions;
 }
}


Vf Page: 

<apex:page controller="ObjectFieldsExampleVF" >
  <apex:form >
   <apex:pageblock >
    <apex:pageblockSection >
     <apex:pageblockSectionItem >
       <apex:outputlabel > Object Name :</apex:outputlabel>
        <apex:selectList value="{!objName}" size="1">
         <apex:selectoptions value="{!myOptions}"></apex:selectoptions>
        </apex:selectList>
     </apex:pageblockSectionItem>
     
      <apex:pageblockSectionItem id="one">
       <apex:outputlabel > <font Color="red">{!objName} - Fields</font></apex:outputlabel>
        <apex:selectList size="1" style="Width:150PX">
         <apex:selectOptions value="{!options}"></apex:selectOptions>
        </apex:selectList>
      </apex:pageblockSectionItem>
     
     <apex:commandButton value="Click Me" action="{!show}" />
    </apex:pageblockSection>   
   </apex:pageblock>
  </apex:form>

</apex:page>







Program to display objects and its fields with dynamic query to display dynamic data in pageblock table.


This we can achieved using dynamic apex.

Class:

public class DynamicTableController {

public List<SelectOption> supportObject{get;set;}

public String selectObject{get;set;}

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Set<String> objectKeys = gd.keySet();

Public List<SelectOption> fieldLabelAPI {get;Set;}

public List<String> selectedFields {get;set;}

public List<Sobject> objectList{get;set;}


 public DynamicTableController (){

  supportObject = new List<SelectOption>();
  selectObject  = '';
  fieldLabelAPI =  new List<SelectOption>();
  selectedFields = new List<String>();
  objectList = new List<Sobject>();
  //Get only reference to objects  
  for(Schema.SObjectType item : ProcessInstance.TargetObjectId.getDescribe().getReferenceTo()){
  //Excluding custom setting objects  
   if(!item.getDescribe().CustomSetting)  {
   supportObject.add(new SelectOption(item.getDescribe().getLocalName().toLowerCase() , item.getDescribe().getLabel() )); 
   }
  
  }
   
 } //end of constructor.

 public void ObjectFields() {
   fieldLabelAPI.clear();
   objectList.clear();
  if(selectObject !='--None--'){
   Schema.sobjectType systemObjectType = gd.get(selectObject);
   Schema.DescribeSObjectResult r = SystemObjectType.getDescribe();
   Map<String, Schema.SObjectField> M = r.fields.getMap();
   for(Schema.SObjectField fieldApi : M.values()){
    fieldLabelAPI.add(new SelectOption(fieldApi.getDescribe().getName(),fieldApi.getDescribe().getLabel()));
   }
  }
 }

 public void showTable(){
  String myQuery = 'Select Id';
  
  for(String field: selectedFields){
   if(field.toLowerCase() != 'id' && field.toLowerCase() !='--None--')
     myQuery +=',' + field+' ' ;  
  }

  myQuery += ' From  '+ selectObject + ' Limit 200'; 
  objectList = Database.query(myQuery);
 }


}

VF Page:

<apex:page controller="DynamicTableController">
 <apex:pageBlock >
  <apex:form >
   <apex:actionFunction name="ObjectFields" action="{!ObjectFields}"/>
  <apex:commandButton value="Show Table" action="{!showTable}"/>
  
  <apex:pageblockSection >
   <apex:pageblockSectionItem >
    <apex:outputlabel value="Select Object"></apex:outputlabel>
     <apex:selectlist multiSelect="false" size="1" value="{!selectObject}" onchange="ObjectFields();">
      <apex:selectOption itemlabel="--None--" itemValue="--None--"></apex:selectOption>
      <apex:selectoptions value="{!supportObject}"></apex:selectoptions>
     </apex:selectlist>
        
   </apex:pageblockSectionItem>  
   
   <apex:pageblockSectionItem >
    <apex:outputLabel value="Select Field"></apex:outputLabel>
    <apex:selectList multiselect="true" size="5" value="{!selectedFields }">
     <apex:selectOption itemLabel="--None--" itemValue="--None--"></apex:selectOption>
     <apex:selectOptions value="{!fieldLabelAPI}"></apex:selectOptions>
    </apex:selectList>
   </apex:pageblockSectionItem>
    
    <apex:pageBlockTable rendered="{!IF(objectList.size >0,true,false)}" value="{!objectList}" var ="rec">
     <apex:column value="{!rec.id}" rendered="{!IF(selectedFields.size==0,true,false)}" />
     <apex:repeat value="{!selectedFields}" var="fieldLabel">
      <apex:column value="{!rec[fieldLabel]}" rendered="{!IF(fieldLabel !='--None--',true,false)}"/>
     </apex:repeat>
   </apex:pageBlockTable>
   
   <apex:outputPanel rendered="{!IF(objectList.size ==0,true,false)}">
    <apex:pagemessage severity="Error" summary="No Records to Display"></apex:pagemessage>
   </apex:outputPanel>
   
   
  </apex:pageblockSection>
  </apex:form>

 </apex:pageBlock>


</apex:page>


output:



Here once the user select the object it will display the fields related to object. then after selecting the fields to query click on show table button it will display the data in pageblock table.

That's it..


More about Dynamic Apex:



Schema Programming in Apex and its usage in Visualforce Page.




1 comments:

prakasam said...

Can we use aura framework instead of visualforce?

Post a Comment

 
| ,