Tuesday, April 17, 2012

Lookup button in Visualforce Page

Example 1:
 <apex:page standardController="Contact">
<apex:inputField value="{!contact.account}"/>
</apex:page>
Example 2:
Apex Class:
public class con {
    public contact c { get; set; }
    public con() {
        c = new contact();
    }
    public void search() {
        // c.accountid has the selected ID.
    }
}
VisualForce Page:
<apex:page controller="con">
   <apex:form>
     <apex:pageblock>
       <apex:pageblocksection>
          <apex:inputfield value"{!c.accountid}"/>
       </apex:pageblocksection>
    </apex:pageblock>
   </apex:form>
</apex:page>

Monday, April 16, 2012

How to implement “Cancel” functionality in a VisualForce Page

Apex Class:

public class sampleExtension {

  ApexPages.standardController std = null;

  public sampleExtension(ApexPages.standardController sc)  {
    std = sc;
  }

  public PageReference doCancel()  {
    return std.cancel();
  }
}

VisualForce Page:
<apex:commandButton action="{!doCancel}" value="Cancel"/>

Note: this doesn't necessarily take you to the list view, it'll return you to the last page you were viewing before going to the VF page.

Reference: 

Saturday, April 14, 2012

Checkbox in DataTable

Displaying the check box in a data table or page block table is a general requirement in every project. with the help of wrapper class we can display the checkboxes in a data table. For the select all checkbox we need to add small javascript so that if we select the header checkbox it will select all the checkboxes.
Apex Class:

public class Checkbox_Class  { 
    List<accountwrapper> accountList = new List<accountwrapper>();
    List<Account> selectedAccounts = new List<Account>();       
    public List<accountwrapper> getAccounts()  {
        for(Account a: [select Id, Name, AccountNumber, Phone from Account limit 5])
        accountList.add(new accountwrapper(a));
        return accountList;
    }
   
    public PageReference getSelected()   {
        selectedAccounts.clear();
        for(accountwrapper accwrapper: accountList)
        if(accwrapper.selected == true)
        selectedAccounts.add(accwrapper.acc);
        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 a)
        {
            acc = a;
            selected = false;
        }
    }
}

VisualForce Page:
<apex:page controller="Checkbox_Class" Tabstyle="Account">
<apex:form >
<apex:pageBlock Title="Accounts with CheckBoxes">
<apex:pageBlockSection Title="List of Available Accounts">
<apex:dataTable value="{!accounts}" 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="Account Name" value="{!a.acc.Name}" />
<apex:column headervalue="Account Number" value="{!a.acc.AccountNumber}" />
<apex:column headervalue="Phone" value="{!a.acc.Phone}" />
</apex:dataTable>
</apex:pageBlockSection>
<apex:pageBlockSection Title="Selected Accounts" id="Selected_PBS">
<apex:dataTable value="{!SelectedAccounts}" var="s" columnswidth="50px,50px" cellpadding="4" border="1">
<apex:column headervalue="Account Name" value="{!s.Name}" />
<apex:column headervalue="Account Number" value="{!s.AccountNumber}" />
<apex:column headervalue="Phone" value="{!s.Phone}" />
</apex:dataTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
<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:page>

Demo : https://sfdevforce-developer-edition.na12.force.com/vfCheckbox

How to check the check box by default in visual force page

Apex Class:

public class checkcontact {

public list<contact> con {get;set;}
public boolean cc{get;set;}

public checkcontact() {
con=new list<contact>();
cc=true;
con=[select name,email from contact];
}

public void change() {
if(cc==false)
cc=true;
else
cc=true;
}

}

VisualForce Page:

<apex:page controller="checkcontact">
<apex:form >
<apex:outputPanel id="p1">
<apex:pageBlock >
<apex:pageBlockTable value="{!con}" var="conlist" >
<apex:column >
<apex:facet name="header"> 
<apex:inputCheckbox value="{!cc}" onclick="change('{!cc}');alert('{!cc}');" />
</apex:facet>
<apex:inputCheckbox selected="true" value="{!cc}" />
</apex:column>

<apex:column >
<apex:facet name="header">Name</apex:facet>
</apex:column>

<apex:column >
<apex:facet name="header">Email</apex:facet>
{!conlist.Email}
</apex:column>


</apex:pageBlockTable>

<apex:actionFunction action="{!change}" name="change" oncomplete="alert('hello');" reRender="p1">
<apex:param name="abc" assignTo="{!cc}" value=""/>
</apex:actionfunction>
</apex:pageBlock>
</apex:outputPanel>
</apex:form>
</apex:page>

Wednesday, April 11, 2012

How to change the column width in Visualforce

<apex:pageblock title="Contacts">
   <apex:pageBlockTable style="width:100%" value="{!contacts}" var="contact">
      <apex:column style="width:250px" value="{!contact.id}"/>
      <apex:column style="width:250px" value="{!contact.Name}"/>
   </apex:pageBlockTable>
 </apex:pageBlock>

Get values of form field in javascript from a visualforce page

<apex:page >
    <apex:form id="myForm1">
        <apex:pageblock id="pb1">
            <apex:pageblockSection id="pbs1">
                <apex:inputCheckbox id="checkbox1" label="Check Me" onclick="javascript:getCheckBoxValue();">
                </apex:inputCheckbox>
            </apex:pageblockSection>
        </apex:pageblock>
    </apex:form>
    <script language="javascript">
        function getCheckBoxValue() {
            alert(document.getElementById('{!$Component.myForm1.pb1.pbs1.checkbox1}').checked);   
        }
    </script>
</apex:page>

Wednesday, April 4, 2012

Different Date Formats Using Apex and Visualforce

APEX:

public with sharing class clsDateFormat {

Datetime myDateTime = system.now();

  List<String> dateFormats = new List<String> {
     'dd.MM.yy HH:mm:ss',
     'MMMMM dd, yyyy hh:mm:ss a',
     'MMM-dd-yyyy hh:mm a',
     'EEEEE dd MMMMM yyyy G',
     'E hh:mm:ss:SSS z',
     'zzzzz (Z), \'Day of the year:\' D'
  };
   
  public DateTime getMyDateTime(){
    return myDateTime;
  }

  public List<String> getDateFormats(){
    return dateFormats;
  }

}

VisualForce:

<apex:page controller="clsDateFormat">
  <apex:sectionHeader title="Date Formatting"/>
    
    <apex:outputText value="Standard Output Format: {!myDateTime}"/>
    
    <apex:pageBlock >
        <apex:pageBlockTable value="{!dateFormats}" var="dateFormat">
            <apex:column headerValue="Date Format" value="{!dateFormat}" width="50%"/>
            <apex:column headerValue="Output" width="50%">
                <apex:outputText value="{0,date,{!dateFormat}}">
                    <apex:param value="{!myDateTime}" />
                </apex:outputText>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Demo https://sfdevforce-developer-edition.na12.force.com/DateFormat

Time Formatting in APEX


Letter Date or Time Piece Examples
G Era G = AD
y Year yy = 09, yyyy = 2009
M Month MM = 08, MMM = Aug, MMMMM = August
w Week in year w = 35
W Week in month W = 3
D Day in year D = 235
d Day in month dd = 27
F Day of week in month F = 2
E Day in week E = Thu, EEEEE = Thursday
a AM/PM a = AM or PM
H Hour in day (0-23) HH = 23
k Hour in day (1-24) kk = 24
K Hour in am/pm (0-11) KK=11
h Hour in am/pm (1-12) hh = 12
m Minutes in hour mm = 30
s Second in minute ss = 55
S Millisecond in second SSS = 888
z Time zone z = EDT, zzzzz = Eastern Daylight Time
Z Time zone offset Z = -0400
Example :
DateTime d = datetime.now();
dateTimeVal = d.format('MMMMM dd, yyyy hh:mm:ss a');
Output :
April 04, 2012 02:40:50 AM

Differences between the Import Wizard and the Apex Data Loader

Salesforce CRM provides two tools for data migration—the Import Wizard and the Apex Data Loader.
The Import Wizard
is designed for less-technical users and smaller, simple imports of up to 50,000 records. It takes you through the process step by step and displays error messages to alert you to potential record duplications ("dupes"). For more information, go to Help & Training | Importing Data | Using the Import Wizards.
Use the Apex Data Loader
for complex imports of any size. It's for technical users only. You'll need access to the API to use this tool, which is included with Enterprise and Unlimited Edition. If you have another edition, you can purchase the API separately by contacting your account executive. The Data Loader doesn't display error messages to alert you to potential problems. However, this tool includes several features that help make large data imports easier, such as being able to save your mappings. For more information, go to Help & Training | Data Loader.
The table below summarizes the difference between the two tools. The instructions in the remaining steps refer to the Import Wizard.
https://www.salesforce.com/assets/images/campaigns/insights_data_migration_table.gif

Field datatype mapping between Oracle/SQL Server and Salesforce

Data type mapping i.e, what data type of Salesforce maps to what data type of SQL Server or Oracle Data Type.
SalesForce Data Type SQL Server Data Type ORACLE Data Type
boolean bit varchar2(1)
date smalldatetime date
datetime Datetime date
currency decimal(precision,scale) number(precision,scale)
double decimal(precision,scale) number(precision,scale)
int Int number(10)
picklist nvarchar(255) varchar2(255)
id nvarchar(18) varchar2(18)
reference nvarchar(18) varchar2(18)
textarea nvarchar(max) varchar2(4000)
email nvarchar(255) varchar2(255)
phone nvarchar(255) varchar2(255)
url nvarchar(255) varchar2(255)
textarea nvarchar(max) varchar2(4000)
multipicklist nvarchar(max) varchar2(4000)
anyType nvarchar(max) varchar2(4000)
percent decimal(5,2) number(5,2)
combobox nvarchar(max) varchar2(4000)
base64 nvarchar(max) varchar2(4000)
time nvarchar(255) varchar2(255)
string nvarchar(length) varchar2(length)

How to format a date in VisualForce?

APEX Class:

public List<Attachment> getCaseAttachmentList(){
  if(caseId != null && caseId != '') {
 string attachCaseQry = 'Select Id, Name, Body, CreatedDate From Attachment where ParentId = \''+caseId+ '\'';
 caseAttachmentList = (List<Attachment>)Database.query(attachCaseQry);
 system.debug('Attachment Result:' + caseAttachmentList);
 
  }
  return caseAttachmentList;
}

VisualForce Page:

<apex:repeat value="{!CaseAttachmentList}" var="attachmentCaseObj"> 
<apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
<apex:param value="{!attachmentCaseObj.CreatedDate}" /> 
</apex:outputText>
<br />
</apex:repeat>

Output:
03/30/2012
04/02/2012
04/01/2012

Monday, April 2, 2012

How to display a custom title on a VisualForce page

if you set showHeader to false, you need to put your own head and title tags in the page, like
<apex:page> 
<head> 
<title>Case: {!aCase.CaseNumber}</title> 
</head>  
<body>
...content...  
</body>
</apex:page>