Saturday, 28 September 2013

Using Custom Label With Trigger


I have seen many of the developer trying to set custom Error Message on Edit page Layout. So here we can do this using Custom Labels.

Custom Label
Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

The purpose of this post is that many time we got a condition to set an error message while writing an Trigger. So here the method to add custom error message on Edit PageLayout

First of all create an Custom Label
Go to
Home --> Setup --> Create --> Custom Labels

The red box or the "Value" field is the error message which is going to be seen by the user on the edit page.


After creating a Custom Label, create a Visualforce page as below which is having an error message

1:  <apex:page >  
2:     <apex:pageMessage severity="info" strength="1" summary="{!$Label.AccountTriggerErrorMessage}"/>  
3:  </apex:page>  

Now add a Trigger on Account Object as below, in this trigger we are adding an error message too.

1:  Trigger TriggerForCustomLabelAccount on Account (before insert, before update) {  
2:  //Check for Event  
3:  if(Trigger.isBefore) {  
4:  //Check for Event Type  
5:  if(Trigger.isInsert || Trigger.isUpdate) {  
6:  //Loop through Account  
7:  for(Account account : Trigger.New) {  
8:  //Check for Account Revenue  
9:  if(account.AnnualRevenue == Null)  
10:  //Here adding error message when condition matches  
11:  account.addError(label.AccountTriggerErrorMessage);  
12:  }  
13:  }  
14:  }  
15:  }  

Now After doing all this, Edit an Account record or create a new one, there will a custom error message on Edit page when condition satisfies.


May the force.com with you, happy coding !!



Monday, 23 September 2013

Dynamically Parsing CSV and loading Data into Objects #Salesforce


Here I have tried to make my work easy in the practice times, so i created my own Custom Dataloader, which requires No Login.

So here it is, I have tried to explain everything in here about the codes working, but if anybody find any problem can contact me. So down here is our first look of Custom Data Loader, here we can only perform three but important DML processes and they are

1. INSERT
2. UPSERT
3. DELETE



Now after choosing your DML Process a new section will be rendered and where we can select our object for the operation, which is a simple picklist but one of the important part of the process.
Here is the snapshot


After choosing your object now you can get upload your file in the next section, yesss....here's a new section will be rendered and a "Choose File" option will help you to upload your CSV file.

But one the important thing to know is that, here mapping of the fields are automatic, the code will map all the fields with the header of the file and upload it, but if there is any spell mistake or if it can't find the field name in the header of your CSV file then it will refuse it to upload and shows error, for example if your CSV file have a header named LastName and you are trying to upload that file in Account Object then it will refuse to upload that field as it cant find one.
Here is the Last snapshot





Here is the Visualforce page code


 <apex:page controller="CustomDataLoader">  
   <script>  
   function ConfirmCancel(){  
     var isCancel = confirm("Are you sure you wish to cancel?")  
     if (isCancel) return true;  
     return false;  
   }   
   </script>  
   <!--second section of DML Operation starts here-->  
   <apex:sectionHeader title="Step 1 of 3" subtitle="Choose Operation"/>  
   <apex:form >   
     <apex:pageMessages />  
     <apex:pageBlock >  
       <!--Button-->  
       <apex:pageBlockButtons location="top">  
         <apex:commandButton action="{!Cancel}" value="Canel" onclick="return ConfirmCancel()" immediate="true" style="width:20%"/>  
       </apex:pageBlockButtons>  
       <!--Page Section-->  
       <apex:pageBlockSection >  
         <!--RADIO BUTTON-->  
         <apex:selectRadio required="true" value="{!dmlOpps }" layout="pageDirection" onselect="{!dmlOpps}" >  
           <apex:selectOptions value="{!Operations}"/>  
           <apex:actionsupport event="onclick" rerender="out" action="{!onclickaction}"/>  
         </apex:selectRadio>  
       </apex:pageBlockSection>  
     </apex:pageBlock>  
   </apex:form>   
   <!-- From here the selection of object process starts-------------------------------------------------------------------->  
   <apex:outputPanel id="out" >   
     <apex:outputPanel rendered="{!IsChecked}" id="out1">   
       <apex:sectionHeader title="step 2 of 3" subtitle="Select Your Object" />  
       <apex:form >   
         <apex:pageBlock >  
           <br/>  
           <br/>  
           <apex:pageBlockSection >  
             <apex:selectList required="true" value="{!selectedValue}" size="1" label="Select Object Name" >  
               <apex:selectOptions value="{!options}"/>  
               <apex:actionsupport event="onclick" rerender="pick" action="{!OnSelectAction}"/>   
             </apex:selectList>   
             <br/>  
             <br/>    
           </apex:pageBlockSection>  
         </apex:pageBlock>   
       </apex:form>  
     </apex:outputPanel>   
   </apex:outputPanel>    
   <!--From Here selection of the file starts---------------------------------------------------------------------------------->  
   <apex:outputPanel id="pick" >   
     <apex:outputPanel rendered="{!IsSelected}" id="pick1">   
       <apex:sectionHeader title="step 3 of 3" subtitle="Choose your .CSV File" id="next2" />  
       <apex:form >   
         <apex:pageBlock >    
           <center>  
             <br/>                            
             <br/>   
             <apex:inputFile value="{!BlobFile}" filename="{!RecordsInTheFile}" accept=".csv" />  
             <apex:commandButton action="{!processingFile}" value="Upload File" id="theButton" style="width:70px;" />  
           </center>  
           <apex:pageBlockButtons location="bottom">  
             <apex:commandButton action="{!Cancel}" value="Cancel" onclick="return ConfirmCancel()" immediate="true" style="width:20%"/>  
           </apex:pageBlockButtons>  
         </apex:pageBlock>   
       </apex:form>   
     </apex:outputPanel>   
   </apex:outputPanel>   
 </apex:page>  

Here is the apex class



/**    Description     :    Custom Data Loader.                               
*
*    Created By      :    Abhi Tripathi   
*
*    Created Date    :    12/04/2013
*
*    Revision Log    :    27/04/2013
**/ 
public class CustomDataLoader{              
    
    //List to hold the options
    public List<SelectOption> options {get;set;}
    public string selectedValue {get; set;}
    
    //DML Operations
    string dmlOpps = null;
    
    //Boolean to load the rest of rhe page when operation is selected
    boolean IsChecked=false;
    
    
    public boolean getIsChecked(){
        return IsChecked;
    } 
    
    //method to check the RadioButton is checked
    public void onclickaction(){
        if(dmlOpps != '' && dmlOpps != null)
            IsChecked = true;
        else
            IsChecked = false;
    }
    
    //choose value
    public List<SelectOption> getOperations() {
        
        //Initiallizing
        List<SelectOption> options = new List<SelectOption>(); 
        options.add(new SelectOption('insert','INSERT')); 
        options.add(new SelectOption('upsert','UPSERT')); 
        options.add(new SelectOption('delete','DELETE')); 
        return options;     
    }
    
    public String getdmlOpps() {
        return dmlOpps ;
    }
    
    public void setdmlOpps (String dmlOpps ){
        this.dmlOpps = dmlOpps ;
    }
    
    //Boolean to load the upload page 
    boolean IsSelected = false;
    public boolean getIsSelected(){
        return IsSelected;
    }
   
    //Method to check the Sobject is selected or not
    public void OnSelectAction(){
        if( selectedValue != null && selectedValue != '' )
            IsSelected = true;
        else
            IsSelected = false;
    } 
    
    //Calling constructor   
    public CustomDataLoader() {                                                                                                     
        
        //memory allocation and default value assignment
        options = new List<SelectOption>();
        options.add(new SelectOption('','Select one'));                                                                 
        
        //Loop through sObject list
        for(Schema.SObjectType sobj : Schema.getGlobalDescribe().Values()) {
            schema.DescribeSObjectResult f = sobj.getDescribe();
            
            //filtering the sobject list 
            if(f.isCreateable() && f.isDeletable() && f.isQueryable() && f.isUpdateable() && f.isAccessible() && f.isUndeletable()){
                
                //populate list with options
                options.add(new SelectOption(f.getName(),f.getLabel()));
            }
        } 
        
        //sorting the list alphabetially   
        options.sort();
    }
    
    //Destination of the cancel Button 
    public PageReference cancel(){
        
        PageReference  pr = new PageReference('/home/home.jsp');
        return pr;
    }                                                                         
    
    //================here starts page 3=====================================================================================
    
    //Defining list, sets and string
    public blob BlobFile{get;set;}
    public string RecordsInTheFile {get;set;}
    public list<Schema.Sobjectfield> sObjectFieldsList {get; set;}
    public set<string> FieldNames{get;set;}
    
    //transient used to limit the page size
    transient list<string> headersList{get;set;}
    transient set<Integer> headersContainedList{get;set;}
    transient list<list<string>> csvRows{get;set;}
    transient String[] ListOfRecordsOnly {get; set;}
    transient String[] ListOfRecordsWithId {get; set;} 
    transient map<string, object> fieldswithDataType;
    
    //Method                                                                             
    public void processingFile(){
        
        //Initiallizing
        FieldNames = new set<string>();
        headersList = new list<string>();
        headersContainedList = new set<Integer>();
        ListOfRecordsOnly = new String[]{};
        csvRows = new list<list<String>>();
        ListOfRecordsWithId = new String[]{};
            sObject dynObject;
        string firsTRecordIds = '';                   
        fieldswithDataType = new map<string, object>();
        
        //Sobject which is selected     
        Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe(); 
        Schema.DescribeSObjectResult r = gd.get(selectedValue).getDescribe(); 
        
        //get name of Sobject
        String tempName = r.getName(); 
        
        //get first 3 digits of the Id
        String tempPrefix = r.getKeyPrefix(); 
        
        //initiallizing
        list<list<Sobject>> listOfListOfSobject = new list<list<Sobject>>();
        list<sObject> dynsObjectList = new list<sObject>();   
        list<object> datatypeOfField = new list<object>();                   
        
        //Fields of sobject
        sObjectFieldsList = Schema.getGlobalDescribe().get(selectedValue).getDescribe().fields.getMap().values();
        
        //Loop over fields list
        for(Schema.Sobjectfield schemaField : sObjectFieldsList) {
            Schema.Describefieldresult FieldResult = schemaField.getDescribe();
            
            //Check if the is updatable or creatable
            if( FieldResult.isUpdateable() && FieldResult.isCreateable()) {
                
                //Populated list with fields label
                FieldNames.add(FieldResult.getName().toLowerCase());
                
                //map of field with corresponding data type values
                fieldswithDataType.put(FieldResult.getName().toLowerCase(), FieldResult.getType());
            }               
        }       
        
        //Check if the no file is selected
        if(blobFile == null){
            
            //Error Message
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.FATAL,'Kindly Choose your File First');
            ApexPages.addMessage(errormsg);
            return;
        }
        
        //file processing
        RecordsInTheFile = BlobFile.tostring();//taking blob file to a string
        headersList = RecordsInTheFile.split('\r\n');//splitting at new line
        
        //list of headers (field Names) only
        headersList = headersList[0].split(',');   
        
        //here defining the records which are having valid headers And removing Id columns and unkwon fields
        integer index = 0;
        
        for(string headerstring : headersList){
            
            //Getting index(List of integers) values of the unknown fields in the csv file                 
            if(!fieldswithDataType.containskey(headerstring.toLowerCase())){                               
                headersContainedList.add(index);
            }
            
            index++;
        }
        
        //list for Indexes with Id also
        set<Integer> IdContainedIndex = new set<Integer>();
        
        //here adding Id column but removing other unkwon fields
        integer WithId = 0;
        
        for(string head : headersList){
            
            //Getting index(List of integers) values of the unknown fields in the csv file
            if(!fieldswithDataType.containskey(head.toLowerCase())){ 
                IdContainedIndex.add(WithId);
                for(integer d=0; d<headersList.size(); d++){
                    if(headersList[d]== 'Id'){
                        IdContainedIndex.remove(d);
                    }
                }
            }
            WithId++;
        }
        
        list<object> MyHeaderMap = new  list<object>();
        
        //get the fields datatype which are in file
        for(string head : headersList){
            
            object mapofFile = fieldswithDataType.get(head.toLowerCase());
            
            //list of object contains data type of fields in the file
            MyHeaderMap.add(mapofFile);                 
        }
        
        //get the CSV lines
        for(String row : RecordsInTheFile.split('\r\n')) {
            
            //add row
            csvRows.add(row.split(',')); 
        }
        
        //Checking for values 
        for(integer j=1; j<csvRows.size(); j++ ){                                                                 
            
            //Record on the rows of this  string
            ListOfRecordsOnly = csvRows.get(j);
            
            //Creating a new sObject dynamically
            dynObject = Schema.getGlobalDescribe().get(selectedValue).newSObject();
            
            for(integer i=0; i<ListOfRecordsOnly.size(); i++){
                
                //Check the index is matching with index of unknownHeaders 
                if(!headersContainedList.contains(i)){ 
                    
                    Object s = null;
                    
                    try {       
                        
                        //processing the datatype of the record and the field
                        if (MyHeaderMap[i]==DisplayType.Double||MyHeaderMap[i]==DisplayType.Currency || MyHeaderMap[i]==DisplayType.Percent){
                            s = decimal.valueOf((String)ListOfRecordsOnly[i]); 
                            
                        } else if (MyHeaderMap[i]==DisplayType.Boolean){                 
                            if (ListOfRecordsOnly[i]=='true'){
                                s = true;               
                            }else if (ListOfRecordsOnly[i]=='false'){
                                s = false;             
                            }else {
                                s = Boolean.valueOf(ListOfRecordsOnly[i]);
                            }
                            
                        } else if (MyHeaderMap[i]==DisplayType.Integer) {
                            s = Integer.valueOf(ListOfRecordsOnly[i]);
                        } else if (MyHeaderMap[i]==DisplayType.Date) {
                            s = Date.valueOf(ListOfRecordsOnly[i]);
                        } else if (MyHeaderMap[i]==DisplayType.DateTime) {                                     
                            s = DateTime.valueOf(ListOfRecordsOnly[i]);
                        } else if (MyHeaderMap[i]==DisplayType.REFERENCE) {
                            id idList = Id.valueOf(ListOfRecordsOnly[i]);
                            s = idList; 
                        } else if ((MyHeaderMap[i]==DisplayType.PickList || MyHeaderMap[i]==DisplayType.PickList) && MyHeaderMap[i]==null) {
                            s = '';
                        }else{ 
                            s = ListOfRecordsOnly[i];
                        }           
                        
                    }catch (System.TypeException e){
                        continue;                                     
                    } 
                    
                    //Put value according with the index in the Sobject variable
                    dynObject.put(headersList[i], s); 
                } 
            }
            
            //adding values in the list of object
            dynsObjectList.add(dynObject);
            listOfListOfSobject.add(dynsObjectList); 
        }             
        
        //Insert=================================================Insert================================================
        
        if(dmlOpps == 'insert'){
            try
            {
                Database.SaveResult[] result = Database.insert(dynsObjectList , false);
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.INFO,'Record Successfully Created');
                ApexPages.addMessage(errormsg);
            }
            
            catch (Exception e)
            {
                
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
                ApexPages.addMessage(errormsg);
                return;
            }   
        }                                     
        
        //list of the Records with corresponding Id's
        list<string> FieldValueWithId = new list<string>();
        sObject ObjectWithIdRecords;//sObject
        list<Sobject> SobjectForUpdate = new list<Sobject>();//List of records
        
        //========================================================upsert===========================================
        
        //Here's is upsert method
        if(dmlOpps == 'upsert'){
            
            //Limiting the loop
            for(Integer k=0; k<headersList.size(); k++ ){
                
                //Check if the Id Column is there
                if(headersList[k]== 'Id')
                    
                    //Loop for the size of the string
                    for(Integer h=1; h<csvRows.size(); h++){
                        
                        //Assigning the value of csvrows to list
                        ListOfRecordsWithId = csvRows.get(h);
                        
                        firsTRecordIds = '';
                        integer b = 0;
                        
                        //List of Id's in the record
                        FieldValueWithId = ListOfRecordsWithId[b].split(',');
                        
                        for(string fvw : FieldValueWithId){
                            firsTRecordIds += fvw.subString(0, 3); 
                        }                                                             
                        
                        b++;
                        
                        //Defining a dynamic object
                        ObjectWithIdRecords = Schema.getGlobalDescribe().get(selectedValue).newSObject();
                        
                        //putting value of field according to the field index
                        for(Integer y=0; y<ListOfRecordsWithId.size(); y++){ 
                            
                            //Check weather is provided or not
                            if(!IdContainedIndex.contains(y)){ 
                                
                                //check if the first 3 digits of Id are same or not
                                if(firsTRecordIds == tempPrefix ){
                                    
                                    //sobject
                                    Object s = null;
                                    
                                    try {       
                                        
                                        //processing the datatype of the record and the field
                                        if (MyHeaderMap[y]==DisplayType.Double||MyHeaderMap[y]==DisplayType.Currency || MyHeaderMap[y]==DisplayType.Percent){
                                            s = decimal.valueOf((String)ListOfRecordsOnly[y]); 
                                        } else if (MyHeaderMap[y]==DisplayType.Boolean){                 
                                            
                                            if (ListOfRecordsOnly[y]=='true'){
                                                s = true;               
                                            }else if (ListOfRecordsOnly[y]=='false'){
                                                s = false;             
                                            }else {
                                                s = Boolean.valueOf(ListOfRecordsOnly[y]);
                                            }
                                            
                                        } else if (MyHeaderMap[y]==DisplayType.Integer) {
                                            s = Integer.valueOf(ListOfRecordsOnly[y]);
                                        } else if (MyHeaderMap[y]==DisplayType.Date) {
                                            s = Date.valueOf(ListOfRecordsOnly[y]);
                                        } else if (MyHeaderMap[y]==DisplayType.DateTime) {                                     
                                            s = DateTime.valueOf(ListOfRecordsOnly[y]);
                                        } else if (MyHeaderMap[y]==DisplayType.REFERENCE) {
                                            id idList = Id.valueOf(ListOfRecordsOnly[y]);
                                            s = idList; 
                                        } else if ((MyHeaderMap[y]==DisplayType.PickList || MyHeaderMap[y]==DisplayType.PickList) && MyHeaderMap[y]==null) {
                                            s = '';
                                        }else{ 
                                            s = ListOfRecordsOnly[y];
                                        }           
                                    }catch (System.TypeException e){
                                        continue;                                     
                                    } 
                                    
                                    ObjectWithIdRecords.put(headersList[y], s);                                             
                                }
                            }
                        }
                        
                        //Add object ot list of object
                        SobjectForUpdate.add(ObjectWithIdRecords);
                    }
            }                                         
            
            if(firsTRecordIds == tempPrefix ){             
                
                //Update Record with database method
                try{
                    Database.SaveResult[] srList = Database.update(SobjectForUpdate, false); 
                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.INFO,'Records Have been Upserted Succesfully');
                    ApexPages.addMessage(errormsg);           
                }
                
                catch (Exception e)
                    
                {
                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
                    ApexPages.addMessage(errormsg);
                } 
            }
        }
        
        //upsert when the Id is not provided
        if(dmlOpps == 'Upsert'){
            
            try
            {
                Database.SaveResult[] srList = Database.insert(SobjectForUpdate, false); 
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.INFO,'Your Records Have Benn Succesfully Created');
                ApexPages.addMessage(errormsg);
            }
            catch (Exception e)
            {
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
                ApexPages.addMessage(errormsg);
            } 
        }
        
        //When delete is chosen=====================================================Delete=======================
        
        list<string> DeletingIds = new list<string>(); 
        if(dmlOpps=='delete'){
            
            //Limiting the loop
            for(Integer k=0; k<headersList.size(); k++ ){
                
                //Check if the Id Column is there
        \        if(headersList[k]== 'Id'){
                    integer idColumn = k;
                    
                    //Loop for the size of the string
                    for(Integer h=1; h<csvRows.size(); h++){
                        
                        //Assigning the value of csvrows to list
                        ListOfRecordsWithId = csvRows.get(h);
                        firsTRecordIds = '';
                        integer b = 0;
                        
                        //List of Id's in the record
                        FieldValueWithId = ListOfRecordsWithId[b].split(',');
                        
                        //first 3 digits of the Id
                        for(string fvw : FieldValueWithId){
                            firsTRecordIds += fvw.subString(0, 3); 
                        }                                                             
                        b++;
                        
                        //List Of Id's Only
                        deletingIds.add(FieldValueWithId[idColumn]);
            
                        //Defining a dynamic object
                        ObjectWithIdRecords = Schema.getGlobalDescribe().get(selectedValue).newSObject();
                        
                        //putting value of field according to the field index
                        for(Integer y=0; y<deletingIds.size(); y++){ 
                            
                            //Check weather is provided or not
                            if(!IdContainedIndex.contains(y)){ 
                                
                                //check if the first 3 digits of Id are same or not
                                if(firsTRecordIds == tempPrefix ){
                                    
                                    //put header column with id's
                                    ObjectWithIdRecords.put( headersList[k] , deletingIds[y]);   
                                }
                            }
                        }
                        
                        //Add object ot list of object
                        SobjectForUpdate.add(ObjectWithIdRecords);
                    }
                }                                         
            }
            
            if(firsTRecordIds == tempPrefix ){             
                
                Database.DeleteResult[] results = Database.delete(SobjectForUpdate, false);
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.INFO,'Records Have been Removed Succesfully');
                ApexPages.addMessage(errormsg);
                
            } else {
                
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
                ApexPages.addMessage(errormsg);
                return;    
            } 
            
            //If the records don't have the column                       
            if(SobjectForUpdate.size()==0){
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Records Dont have ID');
                ApexPages.addMessage(errormsg);                                             
                return;                                           
            }                    
        }   
    }    
}



Happy Coding...!!!! CHEERSSSSS...




Thursday, 12 September 2013

Concept Of StandardSetController For List View Buttons


Why StandardSetController Is Used?
StandardSetController is used when User wants to play with List view records, selected records can be easily called by StandardSetController, just you need to define and declare it.

We can use StandardSetController as below When Using VF List View Button

1:   //Defining standardSetcontroller  
2:      private ApexPages.StandardSetController setController;  
3:      //StandardSetController in Constructor  
4:      public ListViewButtonCreatePDF(ApexPages.StandardSetController setController) {  
5:           this.setController = setController;  
6:      }  
7:      //Method  
8:      public PageReference sobjectSelectedRecords() {  
9:      //List of sObjects  
10:      public List listOfObjects { get; set; }  
11:      //Get selected records  
12:      listOfObjects = (List)standardController.getSelected();   
13:      }  

but if we want to call that page where we are using StandardSetController by a JavaScript List View Button then we cant use this concept of StandardSetController, Because when are using Javascript button then method "getSelected()" stops working.

This is because when we use visualForce button to call our page then there is a direct call between page and the VF button so the above snippet works fine.

So here is the other way to use the StandardSetController for Javascript List View Button

1:  //Defining StandardSetController in Constructor  
2:      public ListViewButtonCreatePDF(ApexPages.StandardSetController setController) {  
3:      listOfObjects = new List();   
4:      //List of Ids  
5:      List ids = new List();  
6:      //Fetch Ids from URL  
7:      String conId = ApexPages.currentPage().getParameters().get('id');   
8:      //Split string     of Ids  
9:      for(String str : conId.split(',')) {  
10:      ids.add(str);  
11:      }  
12:      //Query  
13:      listOfObjects = [Select Id From Contact Where Id =: ids];   
14:      //Paasing List of Contact from StandardSetController  
15:      setController = new ApexPages.StandardSetController(listOfObjects);   
16:      //Set selected records  
17:      setController.setSelected(listOfObjects);   
18:      }  

And then we can use this javascript code for the button when using the above standardSetController concept. In this code we are setting the selected Ids of the records in the URL, and then we can fetch Ids from the URL in the class.

Snippet For Javascript List View Button

1:  //This "records" will have all the Ids of the selected records  
2:      var records = {!GETRECORDIDS($ObjectType.Contact)};  
3:      if (records[0] == null ) {  
4:      alert("Please select at least one record.")  
5:      } else {  
6:      //set "records" to the URL  
7:      window.location = '/apex/YOUR-VF-PAGE?Id=' + records;  
8:      }  

Hope I have helped Some One

Happy Coding..!!!!


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>