Friday 18 May 2012

Wrapper Class

It says in book a Wrapper class is nothing but something that “WRAPS” an object/data type etc so that it can be used. So this means that an object/data type can be extended to perform tasks that wouldn’t be possible otherwise.
When you start your code in Apex you would find that it is really similar to java. Even there we have a wrapper classes to Wrap primitive data type. Example:- An example of this would be assignment of decimal value to a string variable. 

String doubleString = String.valueOf(3.14159);


Coming back to Apex, this is what it says in Salesforce Apex PDF

Now what is a Wrapper Class?!

A class that abstracts common functions such as logging in, managing sessions, and querying and batching records. A wrapper class makes integration more straightforward to develop and maintain, keeps program logic in one place, and affords easy reuse across components.

Examples of wrapper classes in Salesforce.com include theAJAX Toolkit, which is a JavaScript wrapper around the Salesforce.com Web services API, wrapper classes such as Critical Section in the CTI Adapter for Salesforce CRM Call Center, or wrapper classes created as part of a client integration application that
accesses Salesforce.com using the Web services API.

So let’s take an example for this:-

In my opportunity page I would like to show the details of products, and when a user selects the listed record it should be appended in the selected section. Based on the selected records we could perform any task we want by clicking on the command buttons. 

How the page Looks like :-

Wrapper Class - Image 1



















When you selected the items in the “List of Available Products”, it would automatically update the below Selected Products. 


Visualforce Page

<apex:page standardController="Opportunity" extensions="Displayprodsinopprtunity" Tabstyle="Opportunity" >
<script>
function checkAll(cb)
{
var inputElem = document.getElementsByTagName("input");
for(var i=0; i<inputElem.length; i++)
{
if(inputElem[i].id.indexOf("checkedone")!=-1)
inputElem[i].checked = cb.checked;
}
}    
</script>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection Title="List of Available Products" id="ListProd">
<apex:dataTable value="{!Products}"  var="a" columnswidth="50px,50px" cellpadding="4" border="1">
<apex:column >
<apex:facet name="header">
<apex:inputCheckbox >
<apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)" rerender="Selected_PBS"/>
</apex:inputCheckbox>
</apex:facet>
<apex:inputCheckbox value="{!a.selected}" id="checkedone">
<apex:actionSupport event="onclick" action="{!GetSelected}" rerender="Selected_PBS"/>
</apex:inputCheckbox>
</apex:column>
<apex:column headervalue="Product Id" value="{!a.prd.Id}" />
<apex:column headervalue="Product Name" value="{!a.prd.PricebookEntry.Product2Id}" />
<apex:column headervalue="List Price" value="{!a.prd.ListPrice}" />
<apex:column headervalue="Quantity" value="{!a.prd.Quantity}" />
</apex:dataTable>
</apex:pageBlockSection>
<apex:pageBlockSection Title="Selected Products" id="Selected_PBS">
<apex:dataTable value="{!SelectedProducts}" var="s" columnswidth="50px,50px" cellpadding="4" border="1">
<apex:column headervalue="Product Id" value="{!s.Id}" />
<apex:column headervalue="Name" value="{!s.PricebookEntry.Name}" />
<apex:column headervalue="List Price" value="{!s.ListPrice}" />
<apex:column headervalue="Quantity" value="{!s.Quantity}" />
</apex:dataTable>
</apex:pageBlockSection>
<apex:commandButton action="{!updateQuantity}" ReRender="ListProd"  Value="Update Quantity"/>
<apex:commandButton action="{!SendMail}" ReRender="ListProd"  Value="Send Mail"/>
</apex:pageBlock>
</apex:form>

</apex:page>


Controller Class

public class Displayprodsinopprtunity
{

//This is where we have defined the Wrapper Class. 
    public class OpportunityLineItemwrapper
    {
        public OpportunityLineItem prd{get; set;}
        public Boolean selected {get; set;}
        public OpportunityLineItemwrapper(OpportunityLineItem a)
        {
            prd = a;
            selected = false;
        }
    }
// This is the Wrapper Name for the object Opportunity Line Items
    List<OpportunityLineItemwrapper> OppList = new List<OpportunityLineItemwrapper>();
    List<OpportunityLineItem> selectedProducts = new List<OpportunityLineItem>();

//Defines a Map to store all items selected based on the ID from the  ID from the URl.
    Map<Id,OpportunityLineItem> selectedProductsMap = new Map<Id,OpportunityLineItem>();
   

    public Displayprodsinopprtunity(ApexPages.StandardController controller) {

    }
        
    public List<OpportunityLineItemwrapper> getProducts() {
        ID str = ApexPages.currentPage().getParameters().get('ID');         
        OppList.clear();
        
        for(OpportunityLineItem a : [Select Id,Quantity,
ListPrice,PricebookEntry.Product2Id,
 PricebookEntry.Name From OpportunityLineItem
 where Opportunity.id=:str]){
            
            OpportunityLineItemwrapper opplineItem = new OpportunityLineItemwrapper(a);            
            if (selectedProductsMap.get(a.Id) != null)
                opplineItem.selected = true;

            OppList.add(opplineItem);        
        }
        return OppList;
    }
    
    public PageReference getSelected() {
        selectedProducts.clear();
        for(OpportunityLineItemwrapper accwrapper : OppList)
        if(accwrapper.selected == true) {
            selectedProducts.add(accwrapper.prd);
            selectedProductsMap.put(accwrapper.prd.id, accwrapper.prd);
        }
        return null;    
        
    }
    
    public List<OpportunityLineItem> GetSelectedProducts()  {
        if(selectedProducts.size()>0)
return selectedProducts;
        else
return null;
    }    

    public void updateQuantity() {
        List<Id> SelectedIds = new List<Id>();
       
        for(OpportunityLineItem litem: selectedProducts) {            
             OpportunityLineItem updateQuantity = new OpportunityLineItem (Id=litem.Id,Quantity=22); 
             Update updateQuantity ;            
        }      
    }
    
    
     public PageReference SendMail() {
     
Set<Id> SelectedIds = new Set<Id>();
List<Product2> ContactMailID = new List<Product2> ();

for(OpportunityLineItem litem: selectedProducts) {        
SelectedIds.add(litem.PricebookEntry.Product2Id);
}
ContactMailID =[Select ID,Product_Mail__c,productcode 
from Product2 where ID in:SelectedIds];

Set<String> EmailID = new Set<String>();
For(Integer i=0; i < ContactMailID.size(); i++) 
{  
EmailID.add(ContactMailID[i].Product_Mail__c);   
}       
List<contact> SendMail = new List<contact> ();
SendMail= [Select Email from Contact where ID in:EmailID];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toaddress = new String[]{};        
For(Integer i=0; i < SendMail.size(); i++) { 
toaddress.add(SendMail[i].Email);
}       
mail.setToAddresses(toaddress);
mail.setsubject('You have got a mail');
mail.setPlainTextBody('Please check'+ String.valueOf(SelectedIds));
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
return null;
    }
}





I hope this helps in understanding the wrapper class to certain extent.






No comments:

Post a Comment