Sunday, 30 December 2012

Get all the required fields of sObject dynamically?


There is no direct property available in Apex dynamic API to represent the required field. However there is another way to know about it.
If any field have below three properties then it is mandatory field.
  1. If it is Creatable
  2. If it is not nillable and
  3. If it does not have any default value
Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(so.apiName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
List<String> lstrequiredfields=new List<String>();

for(String f : fields.keyset())
{
 Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
 if( desribeResult.isCreateable()  && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
 {
//This is mandatory / required field
      lstrequiredfields.add(f);

 }
}

Getting All fields from an object using dynamic apex


Here in the following snippet

Schema.getGlobalDescribe() returns the map with all sobject types in our org

By using this we can get Sobject type based on api name of object as in second line of snippet.

After getting the sobject type we can get the all the describe result of that object using "getDescribe()" method as in the third line of snippet.

Then we can get all field from that object by using "fields.getMap" as in the the
fourth line of snippet.



Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get('API_Name_Of_SObject') ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;

Create instance of sobject dynamically

Normally the sobject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sobject is going to be instantiated ? Means it will be decided at runtime,then how we handle it .By using dynamic apex we handle it.
See the following snippet.


public SObject getNewSobject(String t)
{

 // Call global describe to get the map of string to token.
 Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

 // Get the token for the sobject based on the type.
 Schema.SObjectType st = gd.get(t);

 // Instantiate the sobject from the token.
 Sobject s = st.newSobject();

 return s;
}

Wednesday, 26 December 2012

Getting Childrelationships from an object using dynamic Apex


If an sObject is a parent object, you can access the child relationship as well as the child sObject using the ChildRelationship object methods.
A ChildRelationship object is returned from the sObject describe result using the getChildRelationship method. For example:

Schema.DescribeSObjectResult   describeresult = Account.SObjectType.getDescribe();//it gives Account  object properties or describe results
List<Schema.ChildRelationship>   lstchildrelationships =describeresult.getChildRelationships(); //It gives you all the childrelationships associated with the account.
To get relationship names from the above list
for(Schema.ChildRelationship relname:lstchildrelationships){
      System.debug('Relationshipname:'+relname.getrelationshipname();
}
Limitation:
You can only use 100getChildRelationships method calls per Apex request.

The following table describes the methods available as part of the ChildRelationship object. None of the methods take an argument.
NameData TypeDescription
getChildSObjectSchema.SObjectTypeReturns the token of the child sObject on which there is a foreign key back to the parent sObject.
getFieldSchema.SObjectFieldReturns the token of the field that has a foreign key back to the parent sObject.
getRelationshipNameStringReturns the name of the relationship.
isCascadeDeleteBooleanReturns true if the child object is deleted when the parent object is deleted, false otherwise.
isDeprecatedAndHiddenBooleanReserved for future use.
isRestrictedDeleteBooleanReturns true if the parent object can't be deleted because it is referenced by a child object, false otherwise.



Thursday, 13 December 2012

Dynamic Apex Example

Here i am going to explain a simple example for dynamic apex.


Here  we have page with a picklist containing all the objects in org.When we select an object from it then it navigates to you to insertion page of selected  object otherwise it simply shows the fields in pageblock table  on visualforce page.

Controller for this page
===================
//This is class for Displaying All objects in picklist
public class AllObjDynamicDisplayClass{

   /* public PageReference fields() {
        return null;
    }*/


    //public String objectName { get; set; }

    public String ren { get; set; }
    public PageReference Fields() {
         Schema.SObjectType gd;
          Schema.DescribeSobjectResult a11;
        if(selectedObj!=null){
              gd = Schema.getGlobalDescribe().get(selectedObj);
              a11=gd.getDescribe();
        }
        pagereference pg;
      //here we are comparing the selected object is creatable or not
        if(a11.isCreateable() && a11.isAccessible() && a11.isDeprecatedAndHidden()==false && a11.isQueryable() && a11.isSearchable())
        pg=new Pagereference('/'+a11.getKeyPrefix()+'/e?');
        return pg;
    }
//we are returning the fields from selected object if it is not creatable
   public List<Schema.SObjectField> getFields(){
    List<Schema.SObjectField> sss=new list<Schema.SObjectField>();
    if(selectedObj!=null){
    sss.clear();
    Schema.SObjectType gd = Schema.getGlobalDescribe().get(selectedObj);
    Schema.DescribeSobjectResult a11=gd.getDescribe(); 
    Map<String, Schema.SObjectField> M = a11.fields.getMap();
    for(Schema.SObjectField s1:m.values()){
        system.debug('----'+s1+'\n');
        sss.add(s1);
    }
   }
    return sss;
}
    public List<SelectOption> items { get; set; }
    public String selectedObj { get; set; }
    public AllObjDynamicDisplayClass(){
        List<Schema.sObjecttype> lst= Schema.getGlobalDescribe().values();//this is used for getting all the objects from org
        items= new List<SelectOption>();
        items.add(new SelectOption('','--None--'));
        for(Schema.sobjecttype s:lst){
       // if(String.valueOf(s).contains('__c'))
            items.add(new SelectOption(string.valueOf(s),String.valueOf(s)));
        }
    }
}

page
========

<apex:page controller="AllObjDynamicDisplayClass" sidebar="false">
    <apex:form >
        <apex:actionFunction action="{!fields}" name="fun"/>
        <apex:pageBlock >
            <apex:pageblockSection ></apex:pageblockSection>
             <apex:SelectList value="{!selectedObj}" size="1" onchange="fun()">
                 <apex:selectOptions value="{!items}"/>
             </apex:SelectList>
                  <apex:pageBlocktable value="{!Fields}" var="f" >
              <apex:column headerValue="{!selectedObj} Field Names" value="{!f}"/>
              </apex:pageBlocktable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
============================

Output:
======

Wednesday, 5 December 2012

Small story for great determination



As for determination, one should follow the example of the sparrow who lost her eggs in the waves of the ocean.


A sparrow laid her eggs on the shore of  the ocean, but the big ocean carried away the eggs on its waves. The sparrow became very upset and asked the ocean to return her eggs. The ocean did not even consider her appeal. So the sparrow decided to dry up the ocean. She began to pick out the water in her small beak, and everyone laughed at her for her impossible determination. The news of her activity spread, and at last Garuda, the gigantic bird carrier of Lord Vishnu, heard it. He became compassionate toward his small sister bird, and so he came to see the sparrow.Garuda was very pleased by the determination of the small sparrow, and he promised to help. Thus Garuòa at once asked the ocean to return her eggs lest he himself take up the work of the sparrow. The ocean was frightened at this, and returned the eggs. Thus the sparrow became happy by the grace of Garuda.  But if anyone follows the principles with great determination, the Lord(helping hand) will surely help, for God helps those who help themselves.

So ,Nothing is impossible in the world even the word impossible says i am possible.

All the best.

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...