Sunday, July 2, 2017

Wrapper class usage in apex and visualforce pages.

A common use case for Visualforce is to present a list of sObjects, allowing a user to select a number of these, and then choose an action to apply to the selected entries. Marking an sObject entry as selected presents a challenge, as it is associating transient information, the selected status, with a record persisted in the Salesforce database.

The solution is to use a wrapper class to encapsulate or wrap an sObject instance and some additional information associated with the sObject instance.

In the below example i developed a visualforce page with delete functionality based on the selected account records. when ever user select's particular account records to delete then wrapper object holds the selected account with check box value as true, then based on the check box value we can able to delete the particular selected account records.

Controller Class: 
Here i am using custom controller to develop the wrapper functionality, HereAccountRecordCls  is wrapper class to have multiple things like  holding the selected account record with check-box value and individual account record.

---------------------------------
Example:
<apex:page controller="Checkbox_Class" Tabstyle="Account">
    <apex:form >
     <apex:pageBlock Title="List of Accounts" >
     <apex:pageBlockButtons >
     <apex:commandButton value="Display the selected Records" action="{!GetSelected}" rerender="Selected_PBS"/>
     </apex:pageBlockButtons>
        <apex:pageblockSection >
            <apex:pageBlockSection Title="List of Available Accounts" columns="1" >
                <apex:pageblockTable value="{!accounts}" var="a1" >
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!a1.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column headervalue="Account Name" value="{!a1.acc.Name}" width="200"/>
                    <apex:column headervalue="Phone" value="{!a1.acc.Phone}" width="300"/>
                </apex:pageblocktable>
            </apex:pageBlockSection>

            <apex:pageBlockSection Title="Selected Accounts" id="Selected_PBS" columns="1">
                <apex:pageblockTable value="{!SelectedAccounts}" var="s"  >
                    <apex:column headervalue="Account Name" value="{!s.Name}" width="30"/>
                  <apex:column headervalue="Phone" value="{!s.Phone}" width="30"/>
                </apex:pageblockTable>
            </apex:pageBlockSection>
</apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>

</apex:page>

Controller:

public class Checkbox_Class

{
     List<accountwrapper> accountList = new List<accountwrapper>();
     List<Account> selectedAccounts = new List<Account>();

  /* public Pagereference displaytheselectedaccounts()
   {
   return null;
   }  */

public List<accountwrapper> getAccounts()
   {
    for(Account a1 : [select Id, Name, AccountNumber, Phone from Account limit 10]){
    
    system.debug('for loop begin..'+a1 );
    accountList.add(new accountwrapper(a1));
    system.debug('for loop ending..'+accountList );
    }
    return accountList;
    }

public PageReference getSelected()
    {
    selectedAccounts.clear();
    for(accountwrapper accwrapper : accountList)
    if(accwrapper.selected == true)
    selectedAccounts.add(accwrapper.acc);
    system.debug('for loop select..'+selectedAccounts);
    return null;
    }

public List<Account> GetSelectedAccounts()
    {
    if(selectedAccounts.size()>0)
    return selectedAccounts;
   else
   return null;
    }

public class accountwrapper
   {
   public Account acc{get; set;}
   public Boolean selected {get; set;}
  public accountwrapper(Account a1)
   {
   acc = a1;
   selected = false;
}
}

}
--------------------------------public class AccountDeleteWrapperCLs{
public List<AccountRecordCls> accWrapperRecordList {get;set;}


 public AccountDeleteWrapperCLs(){
 List<Account> accList= new List<Account>();
 accWrapperRecordList = new List<AccountRecordCls>();
 accList = [select id,Name,Phone,AccountNumber from Account];
  if(!accList.isEmpty()) {
    for(Account acc: accList){
     AccountRecordCls arcls = new AccountRecordCls();
     arcls.isSelected =  false;
     arcls.accObj = acc;
     accWrapperRecordList.add(arcls);
    
    } //end of for loop.
  
  } //end of if condition.
 }
  
  /*
   Delete Account functionality based on the selected records.
  */
  public PageReference DeleteAccount(){
   List<Account> accToDelete = new List<Account>();
   //To hold the unselected account records.
   List<AccountRecordCls> listUnSelectedRecords  = new List<AccountRecordCls>();  
    if(accWrapperRecordList !=null && accWrapperRecordList.size()>0) {
      for(AccountRecordCls wrapObj :  accWrapperRecordList){
        if(wrapObj.isSelected == true){
          accToDelete.add(wrapObj.accObj);
        }else{
          listUnSelectedRecords.add(wrapObj);
        }
      
      
      }//end of for.
      /*
       checking the delete list size and assign the unselected values to 
       original wrapper list.
      */
      if(accToDelete !=null && accToDelete.size()>0){
       delete accToDelete;
       accWrapperRecordList.clear();
       accWrapperRecordList.addAll(listUnSelectedRecords);
      }
    
    }else{
     ApexPages.Message  myMsg = new ApexPages.Message(ApexPages.Severity.info, 'Records were not there to delete.');
     ApexPages.addMessage(myMsg);
    }
    
    return null;
  }

  

 /* Wrapper class with checkbox and account object. 
  this is also  called as inner class 
  */

 public class AccountRecordCls{
  public boolean isSelected {get;set;}
  public Account accObj {get;set;}

 }

}

Visualforce Page: 


<apex:page controller="AccountDeleteWrapperCLs">

 <!-- This i am using for action status message display with processing records information -->

 <style>
    /* This is for the full screen DIV */
    .popupBackground {
        /* Background color */
        background-color:black;
        opacity: 0.20;
        filter: alpha(opacity = 20);
    
        /* Dimensions */
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 998;
        position: absolute;
        
        /* Mouse */
        cursor:wait;
    }

    /* This is for the message DIV */
    .PopupPanel {
        /* Background color */
        border: solid 2px blue;
        background-color: white;

        /* Dimensions */
        left: 50%;
        width: 300px;
        margin-left: -100px;
        top: 50%;
        height: 50px;
        margin-top: -25px;
        z-index: 999;
        position: fixed;
        
        /* Mouse */
        cursor:pointer;
    }
</style>
<apex:actionStatus id="deleteStatus" stopText="">
    <apex:facet name="start">
        <div>
            <div class="popupBackground" />
            <div class="PopupPanel">
                <table border="0" width="100%" height="100%">
                    <tr>
                        <td align="center"><b>Please Wait</b></td>
                    </tr>
                    <tr>
                        <td align="center"><img src="{!$Resource.AJAXProgressBar}"/></td>
                    </tr>
                </table>
            </div>
        </div>
    </apex:facet>
</apex:actionStatus>

 <!-- end of Action Status --> 
<apex:pagemessages id="Msg"> </apex:pagemessages>
<apex:pagemessage summary="Your are doing Mass Delete On Account Object" Severity="Info" Strength="2"></apex:pagemessage>


 <apex:form id="theForm">
  <apex:commandButton value="Delete Account" action="{!DeleteAccount}" reRender="thePb,Msg" status="deleteStatus"/>
  <apex:pageblock id="thePb">
   <apex:pageblockTable value="{!accWrapperRecordList}" var="record">
   <apex:column headerValue="Select">
     <apex:inputCheckbox value="{!record.isSelected}"/>
    </apex:column> 
    <apex:column value="{!record.accObj.Name}"/>
     <apex:column value="{!record.accObj.Phone}"/>
      <apex:column value="{!record.accObj.AccountNumber}"/>
   </apex:pageblockTable>  
  </apex:pageblock> 
 </apex:form>

</apex:page>



Example of using Wrapper class:

1). http://sfdcsrini.blogspot.com/2014/12/adding-and-deleting-rows-dynamically-in.html

2). http://sfdcsrini.blogspot.com/2014/08/displaying-records-in-visualforce-page.html

No comments:

Post a Comment