Difference between action support and action function

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9  ** Article 10

Before understanding the difference between Action support and Action Function let us go through what they do and their similarities:

1. Both action support and action function can be used to call a controller method using an AJAX request.
   * for example call controller onclick of a inputcheck box
   * or call a controller method onfocus of a input field
Well, they both do the same thing of calling controller method.

Difference between both:


1. Action function can call the controller method from java script.
2. Action support adds AJAX support to another visualforce component and then call the controller method.
    for example:

     <apex:outputpanel id="outptpnl">
             <apex:outputText value="click here"/>
         <apex:actionSupport event="onclick" action="{!controllerMethodName}"  rerender="pgblck" />
     </apex:outputpanel>
 
Here action support adds AJAX to output panel, so once you click on output panel controller method will be called.
 
3. Action function cannot add AJAX support to another component. But from a particular component which has AJAX support(onclick, onblur etc) action function can be called to call the controller method.
Example:

 <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckbox onclick="myactionfun" />


In this example onlick of input checkbox "myactionfun" action function is called from where controller method "actionFunMethod" gets called.
Apart from this, the main difference between the "two" action support and action function is that, the action function can also be called from java script.
Example:

<apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckbox onclick="myJavaMethod()" />
<script>
   function myJavaMethod(){
     myactionfun();// this call the action function
  }
  </script>

Here onclick of the inputcheck box java script is called from where the action function gets called and ultimately your controller method.
Lets demo both as a full fledged example:

Click in the Input text to call controller method using action support
Click the input check box to call Java script, then confirm in java script, upon confirmation controller method is called using action function.

Tex in the lower pageblock gets changed depending on whether the controller method is called by action support or action function.












Visualforce Page:

<apex:page controller="ActionSupFunController">
 <apex:form >
  <h1>Demonstration of difference between Action function and Action Support</h1>

  <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/><br></br> <br></br>
 
  Input Text <apex:inputText >
                <apex:actionSupport action="{!actionSupMethod}" event="onclick" reRender="outptText" />
             </apex:inputText> <br></br>
            
Click me to call action function method   <apex:inputcheckbox onclick="myJavaMethod()" /><br></br> <br></br>  

    <apex:pageBlock >
        <apex:outputText value="{!Display_This_String}" id="outptText"/>
    </apex:pageBlock>        

  <script>
   function myJavaMethod(){
   var checkinput = confirm('Are sure you wnat to call action function method?');
   if(checkinput == true)
      myactionfun();
  }
  </script>
 </apex:form>
</apex:page>


 -- Controller --

Public with sharing class ActionSupFunController {
Public string Display_This_String{get;set;}

    Public ActionSupFunController (){
     Display_This_String = 'value set in constructor';
    }
   
    Public void actionFunMethod(){
      Display_This_String = 'value set in action function method';
    }
   
    Public void actionSupMethod(){
      Display_This_String = 'value set in action Support method';
    }
}

 
Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Click For : Salesforce Interview Question And Answers

Account team mass update access level using data loader

Lets take a brief look at what is a account team:

A account team is team or say group of users who work together on a particular account. Each account record may have its own team. Each user of this team will have its role defined. Each user will have its access level defined for Account, Opportunity of that account,Case's of that account.

Account team object has fields OpportunityAccessLevel, CaseAccessLevel, AccountAccessLevel to store value for access levels. Access levels could be private, Read/Write and Read.

Ever tried updating Opportunity access level or Account access level for a account team using data loader?
Well, if you did try and could not find the fields OpportunityAccessLevel or AccountAccessLevel you are not at fault !!!

These fields aren't available in data loader for Account Team object!!

Then, How can we do mass updates for these fields?

We can do this using the account share object. Account share object represents a sharing entry on an Account.
This object stores records that indicate which user or group has what kind of access to a particular account record.

Say for example if Account A can be Read/Write by 2 users user1 and user2 then there will be two entries in account share object plus one more entry for the owner of the account. So total three records which will store the account id, access level, and user id.

As we have seen above that an account team actually consists of users, so there will be one entry in AccountShare for each user that constitutes a account team.
Thus we can update these account share records to update the accesslevels which will ultimately update the Account Team access levels.

Lets discuss an example of account team,
An account "TestAccount" has a account team as below,



So, there will be two records of account share associated with this account(1 for account owner and one for account team member). If there were two account team members the total account share records would have been 3.



So now to update the account team members Opportunity access level or account access level we will need to update this first record in picture.

You just need to give the accountId , userorGroupId and whichever access level you need to give.
Values for Opportunity/AccountAccesslevels needs to be either of these: Edit,Read,None (first letter need to be capital).

If a account share record is inserted and if it matches a existing record then the original record is modified with the new field updates.
For example, in the above case when we created a account team member salesforce automatically created a accountshare record for it.
Here when we tried inserting new account share record for the same account id and user id but with new access level it updated the already existing record with the new access level.


custom settings in salesforce

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9  ** Article 10

Custom settings are are similar to custom objects. A custom object is created by developer, similarly we have to create our own custom setting.

A custom setting like a custom object will have custom fields as per requirement. Once we have object and its fields, we can create records of that object, similarly we can create records of custom setting too(its just that we don't call it a record, otherwise it very well qualifies to be called a record).
We will call it a list of data for our reference.

If custom settings are similar to custom objects, then why do we need custom custom settings in first place? Let us try to understand advantages of custom settings in salesforce
Ans: Custom setting allows us to store set of data and access it without actually querying it in apex. So you save a select query here !

Lets understand this by an example,

Before we start the example its just worth to mention that there are two types of custom settings List and Hierarchical. As of now lets discuss List type. We will also see the difference between list and hierarchy custom settings in salesforce and how they can be used for meeting our requirements.

To understand the usage consider that we have to store data of states and its capital cities. So a state should have its capital associated with it. For this we can create a custom setting and store data in two fields.

Custom setting default gives one field "Name" so this is our name of the state. So we need one more field to store the capital of the state "Capital".






















After our fields are created its time to create the data (States and its capitals) We can create this by pressing "Manage" and then new button.
















All the list of data created can be viewed by pressing manage button:



The above example was for List Type custom setting. Now let us see Hierarchical Custom settings.
hierarchy custom settings in salesforce are similar to List type but in this you can assign data depending on user or profile. You can also have default data. 

For example,

You want to create custom setting for Incentive(you will store incentive amount). So your custom setting will have field Incentive amount. Any organisation will distribute its incentive based on profile/User.
A manager will definitely get more incentive than a Trainee.

So depending on the profile/user incentive be given.

In hierarchical custom setting you have a extra field "Location" here you have to specify the user or the profile.


























Salesforce logically checks the profile/user settings for the current user and returns the specific data to that profile/User.

Now let us address the following question,

How to access custom setting in apex? At times we may need to manipulate the custom settings data in code logic. lets see how we can update custom setting in apex.

Let us access data from List Type custom setting,
In the above example for List type we had custom setting named "States and Capitals" and its api name "StatesandCapitals__c", it had field "Capital__c".
We had data set for this custom setting, so now let us access it in apex.

1. We will access all the states and their capital
2. We will access capital of a particular state

Our code as below,

Public CustomSettingMethod (){
   //Get all the states and their capitals
    for(StatesandCapitals__c saC: StatesAndCapitalsList ){
          System.debug('State Name is #'+ saC.name +'and it s capital is'+ saC.Capital__c);
    }

  //Get capital of a specific state
  StatesandCapitals__c CapitalOfGoa =  StatesandCapitals__c.getValues('Goa');
  System.debug('Capital of goa is -' + CapitalOfGoa.Capital__c );
}

Debug statements can be used to see the data.

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Record duplication validation using configuration only in salesforce

Avoiding duplicate records is a very common requirement we come across. We expect a error message just like how a validation rule gives.

A validation rule, however will not solve your purpose. Before we go ahead we need to address this "What is duplication of a record?".
Answer: it depends on the requirement. It could mean if two fields have repeated values for two records or one field repeated or could very well mean 4 -6 fields repeated with similar values

If it was a single field that determines your duplication, then you can make the field unique and avoid duplication.

Let us address for those who need to take into account say 2 or more fields into account to consider as duplicate record.

Say for example, in account record if account name and account numbers are same for two account records then they are duplicates.

If one thinks logically, this requires querying in the data base to see if such record already exists.

However, We can achieve this using configuration only.

Steps:

1. Create a text field which should be marked unique.

2.You need to write a workflow that runs on create and edit criteria. Update your field created in step one. Use formula to take the new value . It should concatenate all your required fields in it. For example : Account Name & Account Number

This will prevent duplicates and you will not have to clean up your org on a regular basis :-)

Email to salesforce

If you wish to use any email account (gmail,yahoo, using MS outlook) to send emails to your contacts or leads and automatically create task and track this under activity history under those contacts or leads then you will need to configure email to salesforce.


By using email to salesforce you will be able to track activity history for your emails sent to lead/contact in saleforce:

1. activity history under contact
2. activity history under Lead
3. activity history under Opportunity

For example I have a Lead "Ralph nex" and this lead has email address as "ralphParerira@gmall.com".
I contact ralph by sending an email and ask him to meet me. Now i expect salesforce to automatically track this email under activity history, this is when email to saleaforce comes into picture.


Lets understand how this works:

How salesforce identifies the record under which activity history should be added?

Simple ! This is based on the email id in Lead or Contact. Salesforce compares your address in to/bcc with records in salesforce lead/contacts. Only standard email fields are tracked, no custom email fields are tracked.

What about Opportunity? Opportunity does not have standard email field in it.

This is based on the contact Roles. It tracks the email id of the contact in contact roles related list under Opportunity.


What setting do i have to make?

Make following settings in My Email to Salesforce in setup:

1. Set My Acceptable Email Addresses to your email id from which you are going to send the emails.

2.You can tick mark "Always save email attachments" if you wish to save the attachments in saleforce used in emails.

3. Activity history tracking for Opportunity could be omitted by not ticking the box.

4. Use the Email to salesforce Address

Whom should the email be sent and How to use Email to salesforce Address?

1. You will send the email to the email address of lead or contact based on this address either in "To" or "cc" salesforce identifies the record and then creates the activity history.

2. You should keep Email to salesforce Address in bcc if you are sending the email to lead or contact address.

3. If you send a email to a addresss which is not used in any lead or contact then your activity history is made in "My unresolved items"(This needs to be set in My email to salesforce settings). You can navigate this from home page(left side in shortcuts)

4. If you have email communication already going on with some addresses then you can simply forward your next email to "Email to salesforce Address" , it automatically tracks the to, cc addresses from previous communication and creates record for activity history.

What can i do with my unresolved items?

You can assign them to either lead, contact or other standard/custom objects record. Or you can chose to Not assign it to anyone in which case it marks the task as completed.








Visualforce page component for mass delete

A lot number of times we need mass delete functionality on various objects. 

We generally have requirement wherein we have button on related list object from where we need to delete the selected records.

How about creating a code which could be used for every such requirement in your org?

Keeping this requirement in mind i worked on a visualforce component :


You can directly copy this component as it is, you only need to pass the list of records and fields to be displayed in the pageblock table.


 --Component --
## Name = "MassDeleteComponent"

<apex:component controller="MassDeleteController" allowDML="true">
<script type="text/javascript">
     //check/uncheck the selected records in the selected list
    function checkAll(cb,cbid){
            var inputElem = document.getElementsByTagName("input");                    
            for(var i=0; i<inputElem.length; i++){            
                 if(inputElem[i].id.indexOf(cbid)!=-1){                                       
                    inputElem[i].checked = cb.checked;
                 }
            }
    }
</script>

<apex:attribute name="ListRecs" description="list of records passed" type="sObject[]" assignTo="{!sObjList}"/>
<apex:attribute name="listofield" description="List of fields" type="string[]" required="false" assignTo="{!SobjFieldList}"/>
  <apex:form>
      <apex:pageBlock id="pgblck">
          <apex:pageBlockTable value="{!ListWrapperMethod}" var="wrapVar" >
              <apex:repeat value="{!FieldList}" var="fl">
                  <apex:column value="{!wrapVar.sObjRec[fl]}"/>
               </apex:repeat>
               <apex:column >
               <apex:facet name="header">
                      <apex:inputCheckbox id="selectAllChecks" value="{!wrapVar.SelectBox}" onclick="checkAll(this,'eachrow')"/>
               </apex:facet>
               <apex:inputcheckbox value="{!wrapVar.SelectBox}" id="eachrow"/>
               </apex:column>
             </apex:pageBlockTable>
           <apex:commandButton value=" Delete Records " action="{!DeleteSelectedRecs}" reRender="pgblck"/>  
        </apex:pageBlock>
  </apex:form>
</apex:component>

 -- Component controller --

public without sharing class MassDeleteController {
Public List<sObject> sObjList{get;set;}
Public List<String> SobjFieldList{get;set;}
Public List<wrapperClass> WrapperList{get;set;}

    Public List<wrapperClass> getListWrapperMethod(){
         WrapperList =new List<WrapperClass>();
             for(sObject sObj:sObjList){
                 WrapperList.add( new wrapperClass(false,sObj)) ;
             }
             return WrapperList;
        }
   Public List<String> FieldList{
      get{
         List<String> FieldList = New List<string>();
         FieldList = getSobjtFieldList();
         return FieldList;
      }set;
   }
   
   Public Class wrapperClass{
     Public Boolean SelectBox{get;set;}
     Public sObject sObjRec{get;set;}
   
     Public WrapperClass(Boolean checkbx, sObject sObjRecord){
        SelectBox = checkbx;
        sObjRec = sObjRecord;
     }
   
   }
   
    public List<string> getSobjtFieldList() {
       List<String> FieldList = SobjFieldList;
       return FieldList ;
    }
    
    Public string DeleteSelectedRecs(){
      List<sObject> DeleteList = New List<sObject>();
      for(wrapperclass wc:WrapperList){
          if(wc.SelectBox  == true)
             DeleteList.add(wc.sObjRec); 
      }
      delete DeleteList;
      return null;     
    }
}


Lets use our component in an example below:
In this example i am passing fields as strings , we can pass this fields from field set as required(make sure you query the required fields appropriately).

 -- Visualforce page --

<apex:page standardcontroller="Account" extensions="MyController" tabStyle="Account">
       <c:MassDeleteComponent ListRecs="{!ListAcc}" listofield="{!fieldList}"/>
</apex:page>

 -- Controller --

Public class MyController {
Public string MyString_From_Methode{get;set;}
Public List<sObject> accList{get;set;}
Public List<string> fieldstringList{get;set;}
    public MyController(ApexPages.StandardController controller) {
    }

    Public List<String> getfieldList(){
        fieldstringList = new List<string>();
        fieldstringList.add('name');
        fieldstringList.add('Status__c');
        return fieldstringList;
    }
     
    Public List<sObject> getListAcc(){
      accList = new List<sObject>();
      accList = [select name,id,status__c from Opportunity  where status__c != null limit 5];
      return AccList;
    }  
}

action function in salesforce

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Its easy to call a controller method for most of the attributes using action="{!Yourmethode_Name}", but what if you were to call the controller method from java script?

One way to do this is by using Action Function. Expertise will definitely be able to use this in complex scenarios. This post is for those who haven't had hands on action function before and want to know how to use it.


Lets take a scenario and work on it:


You have a checkbox and you are calling javascript function on click of this checkbox. And now once you are in js you wish to modify some variable or do something in your controller class. 

Say you want to put some value for a variable in controller and then display it on your page. this will require calling your class method from js.


Lets understand this by example:

 -- Visualforce page--

<apex:page standardcontroller="Account" extensions="MyController" tabStyle="Account">
    <apex:form >
       <apex:actionFunction name="actionFunName" action="{!ActionFunMethode}" reRender="outputtxtId"/>
       <apex:pageBlock > 
            <apex:outputLabel for="inptCheckBox" value="Check this box to call Controller method from js using ActionFunction" style="color:green;"></apex:outputLabel> 
            <apex:inputcheckbox onclick="javaScrpt()" id="inptCheckBox"/>
       </apex:pageBlock> 
      
      <apex:outputText value="{!MyString_From_Methode}" id="outputtxtId"></apex:outputText> 
    </apex:form> 
    
    <script>
      function javaScrpt(){
       actionFunName(); 
      }
    </script>
     
</apex:page>

 --Controller--

Public class MyController {
Public string MyString_From_Methode{get;set;}

    public MyController(ApexPages.StandardController controller) {

    }

    public string ActionFunMethode(){
     MyString_From_Methode = 'Method called from js using Action function';
     return null;
    }
}
Lets debug this for understanding:

 <apex:actionFunction name="actionFunName" action="{!ActionFunMethode}" reRender="outputtxtId"/> 

In the above statement "actionFunName" is the name given to this action function statement and you should use this name while calling AF in js as you can see in js function below:

function javaScrpt(){
     actionFunName(); //Line 2
}


Line 2 call our action function statement it does not call controller method from here, your controller method will be called from AF statement using attribute action="{!ActionFunMethode}"
ActionFunMethode is the method in your controller class.

Public string ActionFunMethode(){
     MyString_From_Methode = 'Method called from js using Action function';
     return null;
}

This method puts a value for a variable "MyString_From_Methode" which is then displayed in vf page. 

Action function reRenders the outputtext attribute in vf page which displays this variable (that is page is refreshed and now the new value set in method is displayed).
 
Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Click For : Salesforce Interview Question And Answers

Relationship Query use - apex in salesforce

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Sometimes we need list of all the child records of a parent record. For example we may need all the contacts of a account.

These records can be retrieved using relationship query. You can say it to be a query within a query. Before we write a relationship query,

We need to know more about lookup field. every look up field will have a child relationship named assigned to it. we can change this name as desired.

This childrelationship name is used in relationship query to refer to the child object,  so we need to find out this name before we write the query. You can find this just below the api name of the field.

Following screen shot shows the account look field details(you can see child relationship name as "contacts"). 
  
Standard look up's given by salesforce will have fixed child relationship names and cannot be changed.

Custom fields created by user can have CR names as desired by user.

Lets try to get get all the contacts of account in below example:
 * overide a custom button on account with this vf page

 -- VisualForce Page --

<apex:page standardController="Account" extensions="contrller">
  <apex:form >
    <apex:pageblock >
       <!-- Display Account related Contacts -->
       <apex:pageBlockTable value="{!relatedContacts}" var="val">
         <apex:column value="{!val.name}"/>
         <apex:column value="{!val.email}"/>
       </apex:pageBlockTable> 
    </apex:pageblock>
  </apex:form>
</apex:page>


 -- Controller --

public with sharing class contrller {
Public id Current_Acc_Id;

    public contrller(ApexPages.StandardController controller) {
    Current_Acc_Id = controller.getRecord().id;
    }

    public List<Contact> getrelatedContacts(){
        List <contact> conList = New List<Contact>();
        for(Account acc:[select id,name,(select name,id,email from contacts) from account where id=:Current_Acc_Id]){
           for(contact con:acc.contacts)
               conList.add(con); 
        }
        return conList;
    }
}

Note that inner query contact "select name,id from contacts" has childrelationship name as mentioned above.

Suppose if you have a custom object lookup and you want to retrieve the these records under account then you have to follow similar steps as above but make sure you append __r to your child relationship name.

If you have a child object AccountChild__c of account and you want to retrieve this objects records then just change the method as below:

Your field name on AccountChild__c for account look is "AccountChild__c" and child relationship name is "AccountChilds"


-- VisualForce Page --

<apex:page standardController="Account" extensions="contrller">
  <apex:form >
    <apex:pageblock >
       <!-- Display custom object records related to account  -->
       <apex:pageBlockTable value="{!relatedCustObjRecs}" var="val">
         <apex:column value="{!val.name}"/>
         <apex:column value="{!val.Id}"/>
       </apex:pageBlockTable> 
    </apex:pageblock>
  </apex:form>
</apex:page>


-- Controller --
 
public with sharing class contrller {
Public id Current_Acc_Id;

    public contrller(ApexPages.StandardController controller) {
    Current_Acc_Id = controller.getRecord().id;
    }

     public List<AccountChild__c> getrelatedCustObjRecs(){
       List<AccountChild__c> conList = New List<AccountChild__c>();
       for(Account acc:[select id,name,(select name,id from AccountChilds__r) from account where id=:Current_Acc_Id]){
           for(AccountChild__c con:acc.AccountChilds__r)
               conList.add(con); 
       }
       return conList;
    }

}

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Visualforce Component in a visualforce page

Many a times we develop codes which are required again and again. Or may be we require them in a little different fashion.

Best coding would always be reusing something that has already been developed. That saves time and also save number of lines you write in apex.

How about developing a generic vf page? 

Salesforce does allow writing generic vf pages! You have to call the page and pass the parameters you wish to send to the generic page. Salesforce calls this "Vf cmponent". you can write this component by navigating to following:
setup --> Develop --> component -->write your component.
Unlike vf page wherein you start with <apex:page ...> here you have to start as  <apex:component...>

Lets take very basic example to understand how component could be used in vf/apex. Suppose you want to write a component which changes the colour of you text to "red".
That is if you submit your text string to this component it should return you same string but with red colour. 

Below is the example for same:

Your component:

<apex:component controller="VisualForceComponentController">
  <apex:attribute description="input field value" name="InputField" assignTo="{!AssignedToField}" type="String" required="true"/>
  <apex:outputText value="{!InputstringReceived}" style="color:red;"/>
</apex:component>  

Class associated with the component:

Public Class VisualForceComponentController{
Public string AssignedToField{get;set;}
    Public VisualForceComponentController(){
    }

    Public string getInputstringReceived(){
       return AssignedToField;   
    }
}

As an example lets call the above component from a vf page as below:

<apex:page standardController="Account" >
  <apex:form >
    <apex:pageblock >
      <c:VisualForceComponent InputField="My Input value" />
    </apex:pageblock>
    </apex:form>
</apex:page>


Lets debug this now:
<apex:attribute description="input field value" name="InputField" assignTo="{!AssignedToField}" type="String" required="true"/>

This creates a component variable named "InputField" so whenever you call this component you can pass value to this variable. We need to define what kind of data it will hold in this case it type="string"
Also mentioning it as required = "true" makes it compulsory that this value should always be passed when we call this component from vf page

what is assignedTo ? the value received in component needs to be assigned to a variable in class if you wish to access it in class.
Also, this value cannot be accessed in constructor. Hence the method :

Public string getInputstringReceived(){
       return AssignedToField;   
     
}

In the above example we directly access the variable in vf component, that is 
instead of "InputstringReceived"  we could have written "InputField" and still it could have worked.

I accessed it through method just to demo how this variable can be accessed in controller.
We need to make sure that whichever variable is used in assigned to should be defined get;set; and public and should have similar data type.

You can call this component from whichever vf page you want but make sure you pass the string to it.

How to Implement custom pickList in visualforce salesforce

Sometimes we need to display custom data like a picklist field in visualforce page. If we have a picklist field then this can be easily displayed using inputfield tag. But in case of custom values this cannot be achieved using inputfield.  So for this salesforce provided "selectList", "SelectOption", "SelectOptions" attributes. I have demonstrated selectList below for both selectOption and selectOptions below.

   
 --Visual force Page--

<apex:page standardController="Account" extensions="CustomPickListDemo">
  <apex:form >
    <apex:pageblock >
    <apex:panelGrid columns="5">
      
      Select State &nbsp;<apex:selectList value="{!SelectedState}" multiselect="false" size="1">
         <apex:selectOption itemValue="Goa" itemLabel="Goa"/>
         <apex:selectOption itemValue="Maharashtra" itemLabel="Maharashtra"/>
         <apex:selectOption itemValue="West Bengal" itemLabel="West Bengal"/>
      </apex:selectList>
       
       &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Select City &nbsp;<apex:selectList value="{!SelectedCity}" multiselect="false" size="1">
         <apex:selectOptions value="{!City}"/>
       </apex:selectList>
     
     </apex:panelGrid> 
    </apex:pageblock>
  </apex:form>
</apex:page>


-- Controller --

public with sharing class CustomPickListDemo {
Public String SelectedState{get;set;}
Public String SelectedCity{get;set;}
    public CustomPickListDemo(ApexPages.StandardController controller) {

    }
    
    public List<SelectOption> getCity() {
        List<SelectOption> CityOptions = new List<SelectOption>();
        CityOptions.add(new SelectOption('Panaji','PanajiLabel'));
        CityOptions.add(new SelectOption('Kolkata','Kolkata'));
        CityOptions.add(new SelectOption('Pune','Pune'));
        CityOptions.add(new SelectOption('Mumbai','Mumbai'));
        CityOptions.add(new SelectOption('Margao','Margao'));

        return CityOptions ;
    }
}


In this statement <apex:selectList value="{!SelectedState}" multiselect="false" size="1"> variable "SelectedState" will hold the selected picklist value(state) similarly for  <apex:selectList value="{!SelectedCity}" multiselect="false" size="1"> SelectedCity variable will hold the selected city. Parameter size let you define the number of values visibile. For picklist set this to 1. You can also make this field multiselect field but this will not resemble to the standard multiselect provided by salesforce.

In case of selectOption you have to add individual elements, but for selectOptions you can iterate over a list which needs to be formed in controller. In above example "City" list is used in selectOptions.

SelectOption object: Lets debug/Know this open statement SelectOption('Panaji','PanajiLabel')); In this case "PanajiLabel" will be displayed on your page but if you want to refer this in controller the actual value will be panaji. Its always better you keep both label and actual value same. I kept it different just for demonstration purpose.

How to use wrapper class in apex

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Before we see an example of how wrapper class is used we should know what is wrapper class,why wrapper class is used and what makes it required.

What is a wrapper class?

A wrapper class i would say is a custom object defined by programmer wherein he defines the wrapper class properties. Consider a custom object in salesforce, what do you have in it? fields right? different fields of different data types. On similar grounds i can say wrapper class has different data types/properties as desired by the programmer. You can wrap different objects types or any other types in a wrapper class.


Why wrapper class?

Generally collections like "list" can store only one type of data for example "string' or "Account". List<Account> will hold only accounts and List<string> will hold only strings in it. But what if you want to show data on table that should show account record as well as it primary contact data  ? iterating over List<Account> will only allow account records and no contact data. 

In this case you can create a wrapper class having variables account and contact and then create list of that wrapper class. This may look a bit complicated but as you go through an example it will sort out easily.

An example i can think of is.. You want to display a account data in table along with a check box on the right side of the table(checkbox for every row) Well you can very well bind a account checkbox field to this right column but below example is for demonstrating wrapper with a custom checkbox column.


Your table value will iterate through list of wrapper class.For every account and checkbox value(false) You will be storing a new wrapper class records in the wrapper class list. This wrapper calss has properties (Account and Boolean).



-- Visualforce page --

<apex:page standardController="Account" extensions="WrapperDemoClass">
  <apex:form >
    <apex:pageblock >
      <apex:pageblockTable value="{!wrapperObj}" var="Rec">
         <apex:column value="{!Rec.accObj.name}"/>
         <apex:column >
            <apex:inputcheckbox value="{!Rec.checkBox}"/>
         </apex:column>
      </apex:pageblockTable> 
    </apex:pageblock>
    </apex:form>
</apex:page>


-- Controller used --

public with sharing class WrapperDemoClass {
 Public List<WrapperClassEx> WrapperList{get;set;}
    public WrapperDemoClass(ApexPages.StandardController controller) {
      
    }
   
   Public List<WrapperClassEx> getwrapperObj(){
      List<Account> accList = [Select id,name from account limit 5];
      WrapperList = New List<WrapperClassEx>();
      for(Account acc: accList){
        WrapperList.add(New WrapperClassEx(acc,false)); 
      }
      return WrapperList;
   } 
  
   Public Class WrapperClassEx{
     Public Account accObj{get;set;}
     Public Boolean checkBox{get;set;}
    
     Public WrapperClassEx(Account accRec, boolean SelectBox){
        accObj = accRec;
        checkBox = SelectBox;
     }
   }
}

Understand Wrapper class scenarios in salesforce

Wrapper class has many use cases and almost ever developer starts using wrapper class from beginning. Lets see some scenarios where you would need to use wrapper class for building the visualforce functionalities. We know that a location in apex can store only data of one type and when you have data from multiple types then you wont be club them together without a self defined container called as wrapper class.


  • Build a table consisting of rows that have data of different primitive types like integer, string etc
  • Display one object data along with a column to select each rows (a checkbox)
  • One object records with some pictorial depiction column like a colored status bar or anything that isn't part of that object
  • A table consisting of rows that have data from 2 or more objects. For example a row that displays some data from account in addition to data from its associated contact
  • A nested wrapper class that is a wrapper consisting of another class variables.


Using Nested wrapper class in salesforce




public class nestedwrapperclass {
   Public list<firstwarpperclass> fwClassList{get;set;}
   public list<secondNestedWrapClass> sNWrappeclassList{get;set;}
   
    public nestedwrapperclass(ApexPages.StandardController controller) {
      /* build records for first wrapper class list */
        firstwarpperclass fwc1 = new firstwarpperclass('cf-04214','91');
        firstwarpperclass fwc2 = new firstwarpperclass('cf-04215','92');
        firstwarpperclass fwc3 = new firstwarpperclass('cf-04216','93');
        firstwarpperclass fwc4 = new firstwarpperclass('cf-04217','94');
        fwClassList = new list<firstwarpperclass>();
        fwClassList.add(fwc1);
        fwClassList.add(fwc2);  
        
        /* building data for nested wrapper class list*/
        secondNestedWrapClass sNwc1 = new secondNestedWrapClass(fwc1,'NW-00001');
        secondNestedWrapClass sNwc2 = new secondNestedWrapClass(fwc2,'NW-00002');
        secondNestedWrapClass sNwc3 = new secondNestedWrapClass(fwc3,'NW-00003');
        secondNestedWrapClass sNwc4 = new secondNestedWrapClass(fwc4,'NW-00004');
        sNWrappeclassList = new list<secondNestedWrapClass>();
        sNWrappeclassList.add(sNwc1);
        sNWrappeclassList.add(sNwc2);
        sNWrappeclassList.add(sNwc3);
        sNWrappeclassList.add(sNwc4);
         
    }
    
    public class firstwarpperclass{
      public string uniqueId{get;set;}
      public string extesnionScore{get;set;}
      
      public firstwarpperclass(string uId, string exScore){
         uniqueId = uId;
         extesnionScore = exScore;
      }
    }
    /* this is the wrapper class that is nested, that is its one component is another wrapper class variable */
    public class secondNestedWrapClass{
      Public firstwarpperclass fwc{get;set;}
      public string wrappNestedSR{get;set;} 
       
      public secondNestedWrapClass(firstwarpperclass fwcInput,string SRInput){
         fwc = fwcInput;
         wrappNestedSR = SRInput;
      }
    }
}

<apex:page standardController="account" extensions="nestedwrapperclass">
  <apex:form >
     <apex:pageBlock >
        <apex:pageBlockTable value="{!sNWrappeclassList}" var="nw">
           <apex:column value="{!nw.wrappNestedSR}" headerValue="SR Number"/>
           <apex:column value="{!nw.fwc.uniqueId}" headerValue="Unique Id"/>
           <apex:column value="{!nw.fwc.extesnionScore}" headerValue="Extenssion Score"/>
        </apex:pageBlockTable>
     </apex:pageBlock>
  </apex:form>
</apex:page> 

Wrapper class to display records from 2 or more objects in a table











public class acc_ConController {
 Public list<accountNContactData> accConwrapperList{get;set;}
    public acc_ConController(ApexPages.StandardController controller) {
       this.accConwrapperList = new List<accountNContactData>();
       account acc = [select name,id from account limit 1];
       contact con = [select name,id,email from contact where accountid =: acc.id and email != null limit 1];
       accountNContactData acCon = new accountNContactData(acc,con);
       accConwrapperList.add(acCon);
    }
    
    Public class accountNContactData{
      Public Account account{get;set;}
      Public Contact contact{get;set;}
      public accountNContactData(account accinput, contact coninput){
         account = accinput;
         contact = coninput;
      }
    }

}

<apex:page standardController="Account" extensions="acc_ConController">
  <apex:form >
    <apex:pageBlock >
       <apex:pageBlockTable value="{!accConwrapperList}" var="acCon">
          <apex:column value="{!acCon.account.Name}"/>
          <apex:column value="{!acCon.contact.Name}" headervalue="Primary Contact Name"/>
          <apex:column value="{!acCon.contact.Email}" headervalue="Primary Contact Email"/>
       </apex:pageBlockTable>
    </apex:pageBlock>
  </apex:form>
</apex:page>


How to sort wrapper class columns

For sorting primitive data types like integer or string salesforce has built in functionality but to sort custom or developer defined classes like wrapper classes there is no function or method provided by salesforce. 

To sort wrapper class variables we can make use of comparable interface provided by salesforce. 
This was introduced during summer 2012 release. Here is a nice post 
related to how we can use comparable interface to sort wrapper class columns. 

pagination for a wrapper class built table

Almost every time you build a table in visualforce, you are asked to put buttons that help navigate through the table in a better way (that is pagination). The best way to implement pagination is through standard controller but this only supports list of sobject or soql as parameters. 

And thus a table built using wrapper class cannot have pagination using standard controller even if one part of the row consists of sobject data. We can use custom iterator for building pagination for wrapper class table. Use hasNext, next iterators for building the custom pagination logic.

Covering wrapper class in a test class




lets see how we can cover a wrapper class in a test class. Below test class cover our wrapper class controller for nested wrapper class example. 

So as to call the wrapper class we need to instantiate the class using the outer class name like, nestedwrapperclass.secondNestedWrapClass and pass the parameters in the constructor. 

If the wrapper class is getting called from a constructor or different method then you can simply call that method or instantiate the outer class that should automatically call the wrapper class and increase the coverage for your wrapper class. In below example i have specially called each of the 2 wrapper classes just to demo else i could i simply called the constructor of main class to cover both wrapper classes.



@isTest(seealldata=true)
public class nestedwrapperclass_Test{
    
    static testMethod void wrappertestmethod1() {
       Test.startTest();
       account acc = new account(name = 'testname');
       insert acc;
       ApexPages.StandardController sc = new ApexPages.StandardController(acc);
        //nestedwrapperclass nw = new nestedwrapperclass(sc);
        nestedwrapperclass.firstwarpperclass nWclss = new nestedwrapperclass.firstwarpperclass('tstuid','88');
        
       nestedwrapperclass.secondNestedWrapClass nWclss2 = new nestedwrapperclass.secondNestedWrapClass(nWclss,'NS-00001');
       
       Test.stopTest(); 
       
    }
         



Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Click For : Salesforce Interview Question And Answers