Code Samples
This is a place to list code samples - collections of pieces of code that you think will be useful to our community. These are typically small (a few pages of Apex, or Apex and a few Visualforce pages, or a trigger or two) and one-off. If you want to instead create a collaborative coding project, check out Code Share
Samples
Writing a JAVA program to connect to Salesforce.com
This is a step by step guide for JAVA integration to salesforce.com, a starting point for newbies and beginners - Click here
Incident/Ticket Management with Timesheets for Salesforce
Package and Screenshots Available here - Click here
A handy tutorial of how to debug your visualforce pages for UI isses
Available here - Click here
Nested Tables and Nested Queries in Visualforce
Check out a sample page to display nested tables using Visualforce.
Code and screenshot available here - Click here
Style your Visualforce Pages
Now add styles to your Visualforce Pages, make them more appealing and user friendly... Use CSS files as static resources and refer them in your Visualforce Pages.. Learn how --Click here
Customized Database Search
There has always been a need to customize the search feature of salesforce. Use the example provided in the link below, customize it as per your needs and make as much use of Visualforce benefits as possible...
Customized Search and Selection - Click here
Dynamic Picklist using Visualforce
Add values to a picklist dynamically using the UI rather than your administrator going to field level details and adding values..
Developed using Visualforce..
Screenshots and Code available here
Flex and Force.com
This is the "Last 5 Contacts" sample shown during the recent webinar about building apps using Force.com and Adobe's Flex development framework. Integrate into Visualforce with the following:
<apex:page >
<apex:flash src="{!$Resource.ContactDemoSWF}" height="300" width="300"
flashvars="sessionId={!$Api.Session_ID}&serverUrl={!$Api.Partner_Server_URL_160}"/>
</apex:page>
Download the ZIP - Ryan Marples
InvalidPlickListValues
Present Scenerio: You can put invalid data in to your salesforce objects fieldType picklist and multipicklist using Data Uploader or Apex. After Installing: Using this package, user can restrict invaild data entry into salesforce picklist and multi-select picklist fields. Best Part: Method used is Genric. Hence, all logic resides in one class and require host (Triggering condition in the object where you require it's support). It's boom for Data Migration Chaps. Restriction: Also, it have one restriction that objects having more the 10 (picklist + multi picklist) it will treat only 10 of them. For Testing: 1. Install this application in your Org. 2. Create a Tab for Testing object in your org. 3. Try to enter wrong values in picklist and multi-picklist fields via Apex or Datalloader. And you will see it is verifying the values.
Click here to install package - Amit Kumar
Visualforce Sample - PDF Quotes and Email Templates
This code sample illustrates how to use Visualforce to define email templates
Email Verify
This code connects to Cdyne's email verification tool, and validates all Contacts email addresses in Salesforce.com. A custom field called isnotValidEmail was created, and it flags that checkbox after verification.
[Download]
Phone Verify
This php code uses Cdyne's Phone Validation Software to validate all the Contact's Phone numbers in Salesforce.
[Download]
Lead Mass Change Status For PRM
This VF page will allow you to add the Mass Change Lead Status to a Partner Portal List View layout. By default, Salesforce removes this button from PRM Lead View pages, which is present in normal Salesforce Lead Views. To install, copy the code from the zip file and create a new VF page with it. Make sure you set the security for your PRM users to access the page. Create a custom button with the following parameters: - Display Type: List Button - Check "Display Checkboxes (for Multi-Record Selection)" - Behavior: Display in existing window with sidebar - Content Source: Visual Force page - Content: Select the page you created with the downloaded code Then, add your button to the Search Layout for Leads List View for your PRM users.
Click Here For Visual Force Page Code For This Sample -Paul Deschenes, Advologix.com
How To Deploy A Trigger To Production - Contact Update Trigger with Test Class
This trigger automatically updates the owner of a Contact record to the Account Owner on save. Code included has a hard coded value of Owner and Account of the environment where it is deployed.
To Deploy Follow:
- Edit Test Class included and change the OwnerID and AccountID with your values in your environment.
- Open Eclipse.
- Copy the files in the zip to the appropriate trigger and class folders in your project
- Select The TRIGGER file TestClass File in Tree View of the Project Explorere in Eclipse, using CONTROL KEY, you will be able to Select ,Multiple Files in Tree View of Eclipse.
- Right Click -> Force.com -> Deploy to Server.
- Provide your Deployment Environment credentials.
- Click Next and Again Next, now Click Finish o deploy the Test Class and Trigger to production.
- The trigger as well as test class will be test fired.
NOTE: I've made the class @isTest, so that No Actual Modifications to Production data is done, the Test Class execution will be Fired in a Simulated Environment. Test Class has been Commented to help make an understanding of what is being done using the trigger.
Click Here For Trigger Code With Test Class -Varun Chaddha, Advologix.com
jQuery DatePicker Component for Selecting Date in VisualForce Page
This Component When used will place a TextInput with a calendar icon adjacent to the input control, so as to Popup a Calendar and have selected Date inserted in the input control, just like the Date Control of Salesforce, which is currently Bounded to be Used only with Data Bounded Fields.
So this way, you simple place a call like: <c:jQueryPickDate pickDateLabel="Pick Date:" pickDateField="selectDate" value="{!selectedDate}" />
And you will have a Date Control on you VisualForce page.
This control is created using jQuery's DatePicker plugin.
Click Here For Component Code -Varun Chaddha, Advologix.com
Display Multi-Picklist as Many Checkbox Fields in VisualForce
If you need to display a multi-picklist field apart from the standard two-select format (like a set of checkboxes), these functions should help.
Click here for blog post with code
Parse an IETF RFC 4180-compliant CSV File with Apex
While Salesforce does not natively generate IETF RFC 4180-compliant CSV files, for those who are trying to use email services or other code to process CSV files there may be an alternative solution.
Click here for blog post with code. Note: Reading the code becomes much easier if the code is copied and pasted into an editor like the Force.com IDE.
Parse a CSV with APEX
There are many tools to import CSV files, but if you need to work on multiple objects from the same file, you might need to do it in Apex. Here is a CSV parsing function that returns an array (lines) of string arrays (fields). Does not handle newlines in the content though.
public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
List<List<String>> allFields = new List<List<String>>();
// replace instances where a double quote begins a field containing a comma
// in this case you get a double quote followed by a doubled double quote
// do this for beginning and end of a field
contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
// now replace all remaining double quotes - we do this so that we can reconstruct
// fields with commas inside assuming they begin and end with a double quote
contents = contents.replaceAll('""','DBLQT');
// we are not attempting to handle fields with a newline inside of them
// so, split on newline to get the spreadsheet rows
List<String> lines = new List<String>();
try {
lines = contents.split('\n');
} catch (System.ListException e) {
System.debug('Limits exceeded?' + e.getMessage());
}
Integer num = 0;
for(String line : lines) {
// check for blank CSV lines (only commas)
if (line.replaceAll(',','').trim().length() == 0) break;
List<String> fields = line.split(',');
List<String> cleanFields = new List<String>();
String compositeField;
Boolean makeCompositeField = false;
for(String field : fields) {
if (field.startsWith('"') && field.endsWith('"')) {
cleanFields.add(field.replaceAll('DBLQT','"'));
} else if (field.startsWith('"')) {
makeCompositeField = true;
compositeField = field;
} else if (field.endsWith('"')) {
compositeField += ',' + field;
cleanFields.add(compositeField.replaceAll('DBLQT','"'));
makeCompositeField = false;
} else if (makeCompositeField) {
compositeField += ',' + field;
} else {
cleanFields.add(field.replaceAll('DBLQT','"'));
}
}
allFields.add(cleanFields);
}
if (skipHeaders) allFields.remove(0);
return allFields;
}
Click here for blog post with code
Using Silverlight in Force.com applications
You can easily embed Silverlight into your Force.com application and leverage all features the technology provides. In this sample Silverlight communicates with Visualforce page using JavaScript. No API calls required.
Using ExtJS in VisualForce components
The very slick ExtJS JavaScript library can be used to build some nice user interfaces. This blog post has examples of one approach to integrating ExtJS into VF components, including as examples an editable grid for arbitrary objects and tree-structured menus for navigating the Campaign hierarchy.
Google Maps API mashup for Leads, Contacts and Accounts
Simple to use code, just create a new Visualforce page and inject the code. You can even use this for other objects by simply modifying the page controller and field references to point to a custom address field if you wanted to. !! You will need to get your own Maps API key here: Maps API Signup
->This is for Accounts:
<apex:page showHeader="false" sidebar="false" standardController="Account">
<script type="text/javascript" src="http://www.google.com/jsapi?key=[get your key at http://code.google.com/apis/maps/signup.html]"></script>
<script type="text/javascript">
google.load("maps", "2.x");
var addressPoint;
// Call this function when the page has been loaded
function initialize() {
if (GBrowserIsCompatible()) {
var map = new google.maps.Map2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
var address = "{!Account.BillingStreet}" + ", " + "{!Account.BillingCity}" + ", " + "{!Account.BillingState}"+"{!Account.BillingPostalCode}" + "," + "{!Account.BillingCountry}";
var geocoder = new GClientGeocoder();
geocoder.getLatLng(address, function(newPoint) {
if (!newPoint) {
$('#textAddress').html('Bummer! We couldn\'t find the location you have in the Billing Address field. Try entering a new address and reloading the page...');
} else {
map.setCenter(newPoint, 14);
map.addOverlay(new GMarker(newPoint));
var marker = new GMarker(newPoint);
map.addOverlay(marker);
marker.openInfoWindowHtml("<div style=\"float:left;\"><div style=\"font-family: arial, san-serif; padding-left:30px;\"><span style=\"font-weight:bold;\">{!Account.Name}</span><br/>{!Account.BillingStreet}<br/>{!Account.BillingCity}, {!Account.BillingState} {!Account.BillingPostalCode}<br/><br/></div></div>");
}
});
}
}
google.setOnLoadCallback(initialize);
</script>
<style>
.locationGoogleMap {
color:#4A4A56;
font-family:arial,helvetica,sans-serif;
font-size:12px;
font-weight:bold;
left:24.3%;
position:relative;
}
#textAddress {
color:#000000;
font-family:arial,helvetica,sans-serif;
font-size:18px;
height:20px;
left:40%;
position:relative;
}
</style>
<apex:outputpanel id="googleMap" layout="none">
<span id="textAddress"></span>
<div id="contentMap" style="width: 100%; position:relative; margin-top:10px;">
<div id="map" style="height: 300px;"></div>
</div>
</apex:outputpanel>
</apex:page>
->This is for Contacts:
<apex:page showHeader="false" sidebar="false" standardController="Contact">
<script type="text/javascript" src="http://www.google.com/jsapi?key=[get your key at http://code.google.com/apis/maps/signup.html]"></script>
<script type="text/javascript">
google.load("maps", "2.x");
var addressPoint;
// Call this function when the page has been loaded
function initialize() {
if (GBrowserIsCompatible()) {
var map = new google.maps.Map2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
var address = "{!Contact.MailingStreet}" + ", " + "{!Contact.MailingCity}" + ", " + "{!Contact.MailingState}"+"{!Contact.MailingPostalCode}" + "," + "{!Contact.MailingCountry}";
var geocoder = new GClientGeocoder();
geocoder.getLatLng(address, function(newPoint) {
if (!newPoint) {
$('#textAddress').html('Bummer! We couldn\'t find the location you have in the Mailing Address field. Try entering a new address and reloading the page...');
} else {
map.setCenter(newPoint, 14);
map.addOverlay(new GMarker(newPoint));
var marker = new GMarker(newPoint);
map.addOverlay(marker);
marker.openInfoWindowHtml("<div style=\"float:left;\"><div style=\"font-family: arial, san-serif; padding-left:30px;\"><span style=\"font-weight:bold;\">{!Contact.Name}</span><br/>{!Contact.MailingStreet}<br/>{!Contact.MailingCity}, {!Contact.MailingState} {!Contact.MailingPostalCode}<br/><br/></div></div>");
}
});
}
}
google.setOnLoadCallback(initialize);
</script>
<style>
.locationGoogleMap {
color:#4A4A56;
font-family:arial,helvetica,sans-serif;
font-size:12px;
font-weight:bold;
left:24.3%;
position:relative;
}
#textAddress {
color:#000000;
font-family:arial,helvetica,sans-serif;
font-size:18px;
height:20px;
left:40%;
position:relative;
}
</style>
<apex:outputpanel id="googleMap" layout="none">
<span id="textAddress"></span>
<div id="contentMap" style="width: 100%; position:relative; margin-top:10px;">
<div id="map" style="height: 300px;"></div>
</div>
</apex:outputpanel>
</apex:page>
->This is for Leads:
<apex:page showHeader="false" sidebar="false" standardController="Lead">
<script type="text/javascript" src="http://www.google.com/jsapi?key=[get your key at http://code.google.com/apis/maps/signup.html]"></script>
<script type="text/javascript">
google.load("maps", "2.x");
var addressPoint;
// Call this function when the page has been loaded
function initialize() {
if (GBrowserIsCompatible()) {
var map = new google.maps.Map2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
var address = "{!Lead.Street}" + ", " + "{!Lead.City}" + ", " + "{!Lead.State}"+"{!Lead.PostalCode}" + "," + "{!Lead.Country}";
var geocoder = new GClientGeocoder();
geocoder.getLatLng(address, function(newPoint) {
if (!newPoint) {
$('#textAddress').html('Bummer! We couldn\'t find the location you have in the Address field. Try entering a new address and reloading the page...');
} else {
map.setCenter(newPoint, 14);
map.addOverlay(new GMarker(newPoint));
var marker = new GMarker(newPoint);
map.addOverlay(marker);
marker.openInfoWindowHtml("<div style=\"float:left;\"><div style=\"font-family: arial, san-serif; padding-left:30px;\"><span style=\"font-weight:bold;\">{!Lead.Name}</span><br/>{!Lead.Street}<br/>{!Lead.City}, {!Lead.State} {!Lead.PostalCode}<br/><br/></div></div>");
}
});
}
}
google.setOnLoadCallback(initialize);
</script>
<style>
.locationGoogleMap {
color:#4A4A56;
font-family:arial,helvetica,sans-serif;
font-size:12px;
font-weight:bold;
left:24.3%;
position:relative;
}
#textAddress {
color:#000000;
font-family:arial,helvetica,sans-serif;
font-size:18px;
height:20px;
left:40%;
position:relative;
}
</style>
<apex:outputpanel id="googleMap" layout="none">
<span id="textAddress"></span>
<div id="contentMap" style="width: 100%; position:relative; margin-top:10px;">
<div id="map" style="height: 300px;"></div>
</div>
</apex:outputpanel>
</apex:page>
Subscribe related user to sObject record
Subscribe a related user to the chatter feed for a given record. Should work for any sObject that has Chatter Feed enabled, and a related user.
Class, test class and generic sObject for test class included.
This is a link to the shared archive in my google docs. It was the quickest way to do this for now. I may publish more details at a later date. Chatter Feed Class Archive
--P Chittum (Peter Chittum) 10:14, 12 September 2011 (PDT)