Tag Archives: Force.com

Export Data In Excel Using Visualforce Page

Here in below example I have a VF Page “AccountDetails.vf” with parameter of account Id. In that VF Page I’m showing the Account record respective Contacts. And a button that export the Contact records to excel sheet. Another VF Page “ContactExportToExcel.vf” for excel.

Viualforce Page: AccountDetails.vf

<apex:page standardController="Account" extensions="ContactExportToExcel">
    <apex:form>
        <apex:pageBlock title="Hello {!$User.FirstName}!">
            You are viewing the {!account.name} account.
        </apex:pageBlock>
        <apex:pageBlock title="Contacts">
            <apex:pageBlockTable value="{!account.Contacts}" var="contact">
                <apex:column value="{!contact.Name}"/>
                <apex:column value="{!contact.Email}"/>
                <apex:column value="{!contact.Phone}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
        
        <apex:commandButton value="Export To Excel" Action="{!ExportToExcel}"/>  
    </apex:form>
</apex:page>

Remember to pass an Account ID as a query string to this page.

Controller:

public with sharing class ContactExportToExcel {
    
    Public List<String> selectedFieldsList {get;set;}
    Public List<Contact> conList {get;set;}
    
    public ContactExportToExcel(ApexPages.StandardController stdCtrl) {
        Account acc = (Account)stdCtrl.getRecord();
        conList = New List<Contact>();
        conList = [Select Id, Name, Email, Phone From Contact Where AccountId =: acc.Id];
    }
    
    Public PageReference ExportToExcel(){
        selectedFieldsList = New List<string>();
        selectedFieldsList.add('Name'); 
        selectedFieldsList.add('Email');
        selectedFieldsList.add('Phone');
        
        PageReference pgRef = New Pagereference('/apex'+'/ContactExportToExcel');
        pgRef.setRedirect(false); 
        return pgRef;
    }
    
}

Visualforce Page: ContactExportToExcel.vf

<apex:page standardController="Account" extensions="ContactExportToExcel" contentType="application/vnd.ms-excel#Contacts.xls" cache="true">
    <apex:pageBlock >
        <apex:pageblocktable value="{!conList }" var="tab">
            <apex:repeat value="{!selectedFieldsList}" var="field">
                <apex:column value="{!tab[field]}"/>
            </apex:repeat>
        </apex:pageblocktable>
    </apex:pageBlock>
</apex:page>

Output:

Select All Checkbox Using Apex in Visualforce Page

Controller:

public class Sample {
    
    public List<ContactWrapper> allContacts { get; set; }
    public Boolean allChecked { get; set; }
    
    public Sample() {
        allContacts = new List<ContactWrapper>();
        allChecked = false;
        
        for(Contact con: [SELECT Name, Title, Department, Email From Contact LIMIT 10]){ 
            allContacts.add(new ContactWrapper(con));
        } 
    }
    
    public PageReference CheckAll(){
        
        for(ContactWrapper con : allContacts){
            con.selected = allChecked;
        }
        
        return null;
    }
    
    public PageReference ProcessSelectedContacts(){
        
        for (ContactWrapper contactWrapper : allContacts ){
            if(contactWrapper.selected == true){
                /* Do Some Processing */
            }
        }
        
        return null;
    }
    
    public class ContactWrapper {
        
        public Contact con{get; set;}
        public Boolean selected {get; set;}
        
        public ContactWrapper(Contact c){
            con = c;
            selected = false;
        }
    }
}

Visualforce Page:

<apex:page controller="Sample">
    <apex:form>
        <apex:dataTable value="{!allContacts}" var="c" id="contactsTable">
            <apex:column >
                <apex:facet name="header">
                    <apex:inputCheckbox value="{!allChecked}">
                        <apex:actionSupport event="onclick" action="{!CheckAll}" rerender="contactsTable"/>
                    </apex:inputCheckbox>
                </apex:facet>
                <apex:inputCheckbox value="{!c.selected}"/>
            </apex:column>
            <apex:column value="{!c.con.Name}" headervalue="Full Name"/>
            <apex:column value="{!c.con.Title}" headervalue="Title"/>
            <apex:column value="{!c.con.Department}" headervalue="Department"/>
            <apex:column value="{!c.con.Email}" headervalue="Email"/>
        </apex:dataTable>
        <apex:commandButton action="{!ProcessSelectedContacts}" value="Process Selected Contacts"/>
    </apex:form>
</apex:page>

Output:

Get Map Result From SOQL Query in Salesforce

//Creating Map with account id as key and account record as value
Map<Id,Account> accountMap = new Map<Id,Account>([SELECT Id, Name, Site, Rating, AccountNumber From Account LIMIT 100]);
 
//Getting list of account using map.values method
List<account> accList = accountMap.values();
 
//Getting set of account Id's using map.keySet method
Set<Id> accIdSet = accountMap.keySet();
 
//Getting list of account Id's using list.addAll method
List<Id> accIdList.addAll(accIdSet);

SOQL For Loop

Biswajeet   March 19, 2014   No Comments on SOQL For Loop

The SOQL for loops iterate over ALL the sObjects returned by a SOQL query. Here is the syntax for the for loop in SOQL:

Option 1 – (Include the SOQL in the loop definition):

for (someVariables : [soql_query])
{
    //Your Code
}

Note: The variables above must be of the same type as the sObject that are returned by the soql_query. Here’s an example below of a simple for loop function that uses the clauses WHERE and LIKE:

String s = ‘Biswajeet Samal’;
For ( Lead a : [SELECT Id, Name from Lead where Name = : (s)])
{
    //Your Code
}

Option 2 – (Create a list of results (sObject list) first and then loop through them):

// Create a list of account records from a SOQL query
Account[] accs = [SELECT Id, Name FROM Account WHERE Name =  'Biswajeet Samal'];
  
// Loop through the list and update the Name field
for(Account a : accs){
   a.Name = 'Biswajeet Samal';
}

 

Introduction to Salesforce.com Object Query Language (SOQL)

An introduction to Salesforce.com Object Query Language (SOQL):

As a developer looking to extend Salesforce.com, SOQL is very important and powerful aspect of coding. You can use SOQL to build your own custom query stings. These query strings can be used in the following places:

  • Apex statements
  • Visualforce getter methods and controllers
  • In the queryString param passed in the query() call
  • Finally, you can use the Schema Explorer in the Eclipse Toolkit

For those are familiar with SQL, will find some differences.

SOQL uses the “SELECT” statement combined with any filter statements to bring back sets of data. The data sets returned may be optionally ordered as well (just like in SQL).

Here is a basic SOQL Select example:

SELECT field1, field2, field3
FROM an object
WHERE filter statement(s) and (optionally) order the results

If you want to get all the names for opportunities created in the last 30 days.
you would use the following SOQL statement:

SELECT Name
FROM Opportunity
WHERE CreatedDate = Last_N_Days:30

If you want to get all the Leads from  your Salesforce.com account where the email address equals = “biswajeet@somecompany.com” you would use the following SOQL statement:

SELECT ID, Name from Lead WHERE email = 'biswajeet@somecompany.com'

SOQL – COUNT():

Getting the “Count” of results being returned in a SOQL data set is pretty simple as well.
For example, if I wanted to know how many Leads were going to be returned in my SELECT statement above, I can use the COUNT() function below:

SELECT COUNT() from Lead WHERE email = 'biswajeet@somecompany.com'

SOQL – Comparison Operators:

Operator Common name
= Equals
!= Not equals
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
IN In
NOT IN Not in (WHERE clause)
INCLUDES EXCLUDES Applies to multi-select picklists
LIKE Like (see section below)

SOQL – Like Operator:

The LIKE operator provides a way to match partial text strings and includes support for wildcards. Let’s say for a moment we want to find all the Leads where the email domain is the same. For this, we can use a “LIKE” operator.  He is an example of a LIKE statement with the % wildcard.

The placement of the percent sign ‘%’ is key here. I am basically saying, bring me back all the Leads where the email ends with “somecompany.com”. Therefore I place the ‘%’ at the beginning of whatever I am looking for.” Anything to the left of the % sign is ignored in the search. If I didn’t know the full domain I could use the following statement:

SELECT Id, Name from Lead WHERE email  LIKE '%somecompany.com'

This is going to return all the leads where the email contains “somecomp”.

SELECT Id, Name from Lead WHERE email  LIKE '%somecomp%'

Other wildcard is the underscore “_”. Thing is used to match exactly one character.
Note: Unlike with SQL, the LIKE operator in SOQL performs a case-insensitive match.

SOQL – WHERE/OR:

If you want to extend the WHERE clause to include multiple values, you can OR. See the example statement below:

SELECT ProductCode FROM PricebookEntry WHERE CurrencyIsoCode = 'USD' or CurrencyIsoCode = 'GBP'

Taking it a step further, you can evaludate multiple things in the WHERE clause:

SELECT ProductCode,UnitPrice FROM PricebookEntry
WHERE (UnitPrice >= 10 and CurrencyIsoCode='USD')
OR (UnitPrice >= 5.47 and CurrencyIsoCode='EUR')