Tag Archives: Apex

Wrapper Class in Apex

A wrapper class is a class, a data structure, or an abstract data type which contains different primitive data types and objects as a class member variable. We can go for wrapper class when we need to perform some operation in the records using other then object fields in that case we can use it.

Here is an example, I want to display list of account data in a table along with a check box on the right side of the table for every row, and I want to show selected account records in another table.

I’ve created a wrapper class with Account object and a Boolean variable members. Retrieving list of account records and binding it to wrapper class. For every account and checkbox value(false) I’m storing a new wrapper class records in the wrapper class list, and in the Visualforce page the value of pageBlockTable is wrapper class list.

Visualforce Page:

<apex:page controller="SampleController" tabStyle="Account" sidebar="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Show Selected Accounts" action="{!getSelectedAccounts}" rerender="pbTable2"/>
            </apex:pageBlockButtons>
            
            <apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
                <apex:pageBlockTable value="{!accWrapList}" var="accWrap" id="pbTable1" title="All Accounts">
                    <apex:column>
                        <apex:inputCheckbox value="{!accWrap.isSelected}"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}"/>
                    <apex:column value="{!accWrap.acc.Industry}"/>
                    <apex:column value="{!accWrap.acc.Phone}"/>
                </apex:pageBlockTable>
                
                <apex:pageBlockTable value="{!selectedAccountList}" var="acc" id="pbTable2" title="Selected Accounts">
                    <apex:column value="{!acc.Name}" headerValue="Account Name"/>
                    <apex:column value="{!acc.Industry}" headerValue="Industry"/>
                    <apex:column value="{!acc.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
                
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Controller:

public class SampleController{
    
    //Account List and AccountWrapper Class List Variables
    public List<AccountWrapper> accWrapList {get; set;}
    public List<Account> selectedAccountList {get;set;}
    
    public SampleController(){
        accWrapList = new List<AccountWrapper>();
        List<Account> accList = new List<Account>();
        accList = [SELECT Id, Name, Type, Industry, Phone FROM Account LIMIT 10];
        for(Account a: accList) {
            //Add each Account record to AccountWrapperList
            accWrapList.add(new AccountWrapper(a));
        }
    }
    
    public void getSelectedAccounts() {
        selectedAccountList = new List<Account>();
        for(AccountWrapper obj : accWrapList) {
            if(obj.isSelected == true) {
                selectedAccountList.add(obj.acc);
            }
        }
    }
    
    //Account Wrapper Class.
    //This wrapper class contains both the standard salesforce object Account and a Boolean value.
    public class AccountWrapper {
        public Account acc {get; set;}
        public Boolean isSelected {get; set;}
        
        public AccountWrapper(Account a) {
            acc = a;
            isSelected = false;
        }
    }
}

Output:

Passing Parameters from a Command Button to Controller

Sometimes we need to pass parameters to the controller, on click of a Command Button. Here is a simple example how to pass parameters from a Command Button click to controller.

Note: Command Button pass parameters to controller, if we use a rerender attribute. So, here in below example I’ve used a rerender attribute with pageBlock component.

Visualforce Page:

<apex:page standardController="Contact" extensions="SampleControllerExtn">  
    <apex:form>
        <apex:commandButton value="Click Command Button" action="{!processCommandLink}" rerender="pb">
            <apex:param name="firstName" value="{!Contact.FirstName}" assignTo="{!firstName}"/>
            <apex:param name="lastName" value="{!Contact.LastName}" assignTo="{!lastName}"/>
        </apex:commandButton>
        <apex:pageBlock id="pb" rendered="false"></apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:

public class SampleControllerExtn {
    
    //Variables being set from the commandlink
    public String firstName {get; set;}
    public String lastName {get; set;}
    
    //Initialize the controller
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        
    }
    
    //Handle the action of the commandLink
    public PageReference processCommandLink() {
        System.debug('Contact Name - ' + firstName + ' ' + lastName);
        //Process the variable with your logic
        return null;
    }
}

Pass Parameters from a Command Link to Controller

Sometimes we need to pass parameters to the controller, on click of a Command Link. Here is a simple example how to pass parameters from a Command Link click to controller.

Visualforce Page:

<apex:page standardController="Contact" extensions="SampleControllerExtn">  
    <apex:form>
        <apex:commandLink value="Click Command Link" action="{!processCommandLink}">
            <apex:param name="firstName" value="{!Contact.FirstName}" assignTo="{!firstName}"/>
            <apex:param name="lastName" value="{!Contact.LastName}" assignTo="{!lastName}"/>
        </apex:commandLink>
    </apex:form>
</apex:page>  

Apex Class:

public class SampleControllerExtn {
    
    //Variables being set from the commandlink
    public String firstName {get; set;}
    public String lastName {get; set;}
    
    //Initialize the controller
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        
    }
    
    //Handle the action of the commandLink
    public PageReference processCommandLink() {
        System.debug('Contact Name - ' + firstName + ' ' + lastName);
        //Process the variable with your logic
        return null;
    }
}

Encrypt and Decrypt a String in Apex

Sample Code:

//Data to encrypt
Blob data = Blob.valueOf('Biswajeet Samal');
//Generate an AES key for the encryption. 
Blob cryptoValue = Crypto.generateAesKey(256);
//Encrypt the data and have Salesforce.com generate the initialization vector
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoValue, data);
//Decrypt the data - the first 16 bytes contain the initialization vector
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoValue, encryptedData);
//Get decrypted data 
String decryptedDataString = decryptedData.toString();
System.debug(decryptedDataString);

Get IP Address of User in Apex

Apex Class:

public class IPAddressController
{
    public string IPAddress {get;set;}
    
    public IPAddressController() {
        
        IPAddress = ApexPages.currentPage().getHeaders().get('True-Client-IP');
        //Get IP address when no caching (sandbox, dev, secure urls)
        if (String.isBlank(IPAddress)) {
            IPAddress = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
        }  
        if (String.isBlank(IPAddress)) {
            IPAddress = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
        } 
    }
}

Visualforce Page:

<apex:page controller="IPAddressController">
    Your Login IP Address : {!IPAddress}
</apex:page>

Output: