Skip to main content

Posts

Showing posts with the label code sample

Top four design patterns and algorithm that every Salesforce Developer should know

A few days ago I was speaking to a developer friend, he was asked about a Singleton design pattern and he had no idea about. He spoke about how we developers never talk about patterns. And that time it hit me, we developers do not talk about design patterns and algorithms. There are many design patterns available off the shelf, they talk in detail about the problems they can solve. However, in my experience, I have come across and used the following 1. Singleton This is one of the most common and important design pattern to be used. When initiating objects, we need to make sure only one instance of the object is initiated. In a multi-tenant system like Salesforce, it becomes imperative that we do not hog more resources than needed Lets look at an example trigger AccountTrigger on Account (before insert, before update) { for(Account record : Trigger.new){ AccountMasterRecordType rt = new AccountMasterRecordType (); .... } } public class AccountMa...

Cache me if you can: What you should know before daring to set URL parameter on visualforce

Photo by John- Mark Kuznietsov http://stocksnap.io  If someone gave me a pence for every time there was an SOQL query in an APEX Class without using Limit or a condition during a code review, I could afford a Lamborgini this month. Sigh. If only. We make it a habit of going digging for data, at the very moment we need it. The crux of this problem happens when you have chain classes which are independent of each other. Each class needs the reference from a single record and we have to query for that record every single time. While we don't see it, every SOQL query has a cost to it, and it does not go in my Lamborghini fund, however, it should. In a recent project, we had to construct an Account 360 page that could fetch information from different integration points. The page was also called using a live telephony integration, which could pass the phone number for the account. This required an ability to keep in context the Account that was on call. Platform Cac...

The curious case of the custom redirection on Salesforce Console

Every developer worth their salt knows that the easiest way of redirection from a page to another is by using everyone's favorite function public PageReference redirect() { PageReference pageRef = page.peskyProblemRedirection; pageRef.setRedirect(true); return pageRef; } And the method is called by adding it to the Action attribute of the CommandButton or link, which works like charm and the user is redirected to the page after completion of the action. So why am I going back to the basics? Because this way of redirection causes a pesky little problem in using the Service Cloud or Sales Cloud console. Let's illustrate the problem, let's say you have a visualforce page as follows: <apex:page sidebar="false" showHeader="false" controller="myExampleController"> <apex:form > <apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton action="{!Re...

Code-pattern for Creating Mind-blowing Tabular Reports on Visualforce (With Sample code)

Salesforce.com has a mind-blowing reporting structure but it limits on data that is available on the system. Can we report on Data that is not present in the system? For e.g., in a time-sheet management system, can we identify the people who have not filled time-sheets for a particular day? Can we report on data that is not present in the system? Can we identify records that are not created? There is one thing I have learned working on Force.com platform for last 7 years, there is No No answer in Salesforce. Think a little bit and the answer will reach you. It is somewhat like climbing mount Everest, can you do it? Sure yes, in how many days depends on how fit I am (or how crazy I am) Ok that Everest thing came up because someone did ask me that a few weeks back, moving on. Someone did also ask me about creating a report on missing details and I gave it a thought. The short answer is Yes we can, the long answer is we write a Visualforce page, anyone can tell you that. But what I r...

Improving the user experience using visualforce

One of the biggest question customers have when implementing a CRM solution is how much can we automate the process? Considering that the representative will be spending 8-9 hours on the computer operating on CRM, the biggest question they ask is, 'Are you making my life easier or harder?' During a recent conversation on twitter this question popped up again. Is it possible to auto-populate the values on a visualforce page on choosing a lookup? Lets say you are designing a custom contact manager page. The page contains 4 fields from Account on the page including a lookup. When the user chooses a account value from lookup he would like to see the other 3 fields automatically populated, Sample visualforce code <apex:page standardController="Contact" extensions="AutopopulateController"> <apex:form> <apex:pagemessages id="msgs"/> <apex:pageblock title="Contact Create/Edit"> <apex:pageblocksec...

Five things to do while writing an apex code to prevent pulling your hair out later.

A new intern joined the team excited to learn about Salesforce. She had a little Java background and thought that Salesforce was very easy compared to Java. In her eagerness, she wrote a 20 lines of code to prove her skills and grasp on Salesforce. The problem was, the code could be written in just 3 lines. When you are coding on Salesforce, you have to keep in mind the following things: i) If you can save some lines of code, save it, you can use those lines later.  If you can write a code in 5 lines, don't waste a 6th one. That one line you saved could be the difference between spending a weekend in office optimizing the code or going to a party at the weekend. ii) Write like the code will run forever. Yes, your Sales team has taken in writing that there will only be three records in the system. Yes, you have written a good code for that. But when you are dealing with Salesforce, remember that data is going to increase over a period of time. Today you may be processing ...

Solution for ActionSupport on Lookups for a Visualforce Page

Hello there, There are two reasons why you are on this page, one is that you like to go through Force.com blogs and gain as much knowledge as you can. Its a good thing, only you won't gain any knowledge reading the blogs but by digging. Two, you are highly frustrated and have Googled extensively for keywords 'ActionSupport', 'Lookup' and 'Visualforce' for many hours and before that were struggling with ActionSupport, onblur, onChange and other events. If you are here for second reason, we both sail in the same ship and even though I may sound like a telemarketer who is keen on wasting your time, I however, would like to inform you that I am sympathetic towards you. After having struggling to get this thing work on a Lookup for a long time, I decided to embark on the journey that took me back in time even before Salesforce.com existed. I went to the very depths of DOM and source code. Right to the birth place... ok not really, but I am just back from Star...

Forcing Opportunity Creating During the Lead Conversion Trigger

Lead Conversion is a process in Sales Cloud that helps users convert leads into related accounts and open new opportunities. This is useful in preventing rework of transferring data from lead fields to Account fields. The entire process of Copy Paste is done with a single touch of button and the data is transferred. However, on business end, the customer has just closed the deal and now the company has earned an Account  Salesforce allows you to streamline the business processes by field mapping. We can map custom fields on Lead object to Custom Fields on Contact, Opportunity or Account object using field mapping on Lead setup. However, there are times when we need to extend the standard the Convert functionality for a more complex purposes for e.g., 1. Transferring some related object from lead to Account, Opportunity or Contact. 2. Throwing an Error if the Opportunity is not created on Conversation In this example I am going to create a trigger ...

The Basics of writing a Apex Trigger

One of the most important and common asked question on Forums and everywhere is how do I write a trigger. Coding in Apex Trigger is like going to a dentist for a root canal, you keep dreading the moment until you realize it is actually not going to hurt you. If you plan to write an Apex Trigger this quick guide will help you doing so. The first and foremost rule in writing a trigger is to remember the oldest suggestion given to the most comprehensive Hitchhikers Guide to Galaxy, ' Don't Panic. ' Writing a trigger is not a rocket science, in-fact we should thank the team at Salesforce and ForceDotCom for making everything so simple, that anyone can do it. Enough of talk, lets code. So you want to write a trigger. Let us have a glimpse of what we are going to build. The problem statement is as follows Problem:  When the User is entering the Opportunity, check for the Opportunity Amount. If the Opportunity Amount is greater than 50,000. Mark the Parent Account as ...

Some PDF tricks on Visualforce: Landscape, A4, page number and more

The beauty of Visualforce is simplicity. Remember the shock you received when you were told the entire page renders as PDF if you just add renderAs=PDF to the Page tag. For those who thought I spoke alien language right now, here is the trick, to render a page as PDF, we add a simple attribute to the <apex: page> tag <apex: page renderAs='pdf'> This will render the entire page as PDF. Now, say we need to add some extra features to the PDF. Like a page number in the footer or we need to render the page in landscape mode. Faced with this problem, I put on my Indiana Jones hat and went hunting for it in the vast hay-sack of the internet (read: googled extensively). Imagine my happiness when i found a big big page with many big big examples to solve the problem. The document I am referring to is from W3C, paged Box media . Long story short, I now possess the ultimate secret of rendering the page in any format I want. So here are few tricks I learned...

Loading animation on Visualforce

Maybe its just be but even if you build the most amazing system in the world, it won't be awesome if it is not visually pleasing or beautiful UI. No font should not be uneven, or the images should not haywire. Everything should be in order. Perfect. A simple script can save you a long email, informing you that a million dollar system is broken because it does nothing when users click the buttons. If you have a long processing happening in the background, its not good to assume your users are psych to know whats happening in background (if only we could see data packets send one by one).  If you do not show them that something is happening, they will end up clicking the button again and again, sending multiple request to the server. Worst case scenario your system will be returned back with a thank you note that excel sheet was better, this is broken. Have no fear, I am here. If you have been following this blog for some time, I hope you do, you will know t...

Dynamic Approval Process on Salesforce

Ever come across the need of a large approval process where you do not know who the approver of the next stage will be? We all do don't we? In a recent project requirement, I had to work on a big approval process. My basic requirement was: 1. One approval process for child object 2. Once child is approved, it should trigger the master object approval process Both the approval process had around 5 steps and the approvers where determined by the role hierarchy and the region of the submitter. Yikes is it? Pre-requisites: For this recipe, you need 1. Basic knowledge of APEX and trigger 2. Basic knowledge of Approval process 3. Aspirin (just in case you miss a step and have to debug it!!!) So lets begin with the Child Object Dynamic Approval process. Steps for Child Object Dynamic Process 1. Create two fields on the child object. These fields will not be shown on Page Layout.        i) Approval_step__c: Text field to determin...

Generating Barcode image on Visualforce and Formula Field: Salesforce Code Tip

Can we generate bar-code image on Visualforce? Yes, Can we make it a field on page layout? Also yes. There are many API's available that help us achieve that. One such API is from  http://www.searchupc.com . The API is very easy to use. Visualforce usage: 1. The {!variable} will possibly be the SobjectVariable ({!sobject.fieldname}) or some {!variable} that stores the UPC code(possibly generated from algorithm.) The output: Formula Field Usage: i) Create a formula field with output as 'Text' ii) Use the below formula, replacing the mergeField with the field you store your UPC number. image("http://www.searchupc.com/drawupc.aspx?q="+ mergeField ,"Barcode") The Output: Works like a charm. Word of Caution:  i) The API accepts only 12 and 13 digit of UPC number. Any other digit and it does not render image. ii) The data is obviously not secure as we are passing the UPC code as a plain text to the server, there is a risk of packet sni...

Displaying Aggregate result on Visualforce using SOQL

There are some who jump out of bath-tub nearly naked when they are highly excited, fortunately I am not one of them, but when I saw the Aggregate functions in Spring 10 release, I was nearly in tears, ok, thats too dramatic but Aggregate functions giving a very beautiful meaning to data altogether. For those of you who knew SQL you obviously know what aggregate functions are and how they beautify your code. Those who do not know, aggregate functions help you aggregate the date based on certain field. Say for example, you want to show the count and Opportunities created on a day, you can aggregate them using SOQL. AggregateResult[] groupedResults = [SELECT Name, Count(Amount) FROM Opportunity GROUP BY CreatedDate]; So how do we display it on Visualforce: Just iterate on the AggregateResults and get elements one by one. for (AggregateResult ar : groupedResults) { System.debug('Created Date' + ar.get('CreatedDate')); } A few pointers for debugging: 1. Alw...

Easiest AJAX Pagination on Visualforce

There are two ways of writing a code, the hard way and the best way, Of-course the hard way is the easy way and best way if always hard way. If this sentence seems hard to understand, understand it is for the best. When developing a VF page, the most important we need is pagination, throwing the large chunk of data on user screen is going to give the user goose bump. After trying a dozen method I came to know the easiest way of implementing pagination using standard set controller on a custom controller. The demo of the code is available here The visualforce Page: <apex:page controller="OpportunityPagination" showheader="false"> <apex:form>             <apex:pageblock id="ThePageBlock">                 <apex:pageblocktable value="{!opportunities}" var="o">                     <apex:column value="{!o.name}">       ...

Creating a multilevel dependent picklist on Visualforce inside a Data table

Recently on working on a project I cam across a serious issue, creating a multilevel picklist with N-Level dependency. e.g., Picklist one, select option, picklist two displays related values, select a value and the data for Picklist 3 are filtered based on picklist 1 and 2 and this goes on. Lets increase the complexity a bit, you want to have this functionality in a data table with multiple rows. The code for this seems tricky, but I did manage to write some. The trick is create a wrapper class within you Apex:Class and bind it with the SelectList. VF Page: <apex:actionRegion > <apex:pageBlockSection id="theSection" rendered="{!noLob}"> <apex:dataTable value="{!packages}" var="field" id="thetable" cellpadding="3px" id="dt"> <apex:column headerValue="Action"> <apex:CommandButton action="{!copyRow}" value="Copy" rerender="theSection" status=...

List View Editing of Accounts

Imagine if you can have a list view of Accounts where users can view accounts, edit accounts in place? Well, it will be the most user friendly system. Obviously, best practice is, open the list view with less fields and then allow users to edit the page with the less number of fields and if they wish to see details, have a detail page link. The following code does just this for you. VisualForce Page: inPlaceAccounts.page <apex:page controller="AccountsController" tabstyle="Account"> <apex:sectionheader subtitle="{!$User.FirstName} {!$User.LastName}" title="Quick Edit Accounts"> <apex:pagemessages> <apex:form> <apex:actionfunction action="{!saveEditAcc}" name="saveEdit"> <apex:pageblock title="Add New Account"> <apex:pageblocksection> <b>Name:</b> <apex:inputtext value="{!newAccount.Name}...

Displaying please wait ajax animation on Visualforce page

Many times there comes a need to display a please wait icon while doing a ajax call on a VF page. This also looks cool for UI. The beauty of VF page is, large things can be achieved with small efforts. Here is a three line of code that will help you achieve the flower. <script> // To show / hide waiting-flower icons function setVisibility(id, isVisible){ document.getElementById(id).style.visibility= isVisible ? 'visible' : 'hidden'; } function show(id){setVisibility(id,true);} function hide(id){setVisibility(id,false);} </script> <apex:actionstatus id="pleasewait" onstart="show('img_status_product_select');" onstop="hide('img_status_product_select');"> <img height="20px" id="img_status_product_select" src="%7B%21$Resource.AjaxAnimation%7D" tyle="visibility:hidden" width=...