Friday, December 28, 2012


Well few days ago while working with a Visualforce page I came across a requirement of showing currency field using proper currency formatting.


For Example

  • 6000 should appear as $6,000.00 in the vf page

After checking the standard Salesforce tags I was unable to find a solution. but somehow figured out that <apex:param> tag can be exploited here.

So do the currency formatting in a vf page you can use the below markup.

<apex:outputText value="${0, number, ###,###,###,##0.00}">  
      <apex:param value="{!Account.Amount__c}"/>  
 </apex:outputText>  

Hoping this helps for your currency formatting need!

Saturday, December 1, 2012


The Salesforce Winter 13 arrived with loads of new methods and upgrades.
From the long list of methods, Salesforce also  has provided a new method "getSObjectType()" for ID data type. This comes with lot relief as prior to API 26.0 there were no such method available by which we can get the sObject Type from Id of the sObject, instead we have to describe every object and match the prefix with the given sObject. A very resource hungry process.


 Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();  
 Schema.DescribeSObjectResult r = gd.get(sObj).getDescribe();  
 String tempName = r.getName();  
 String tempPrefix = r.getKeyPrefix();  
 String ObjId= [SELECT Id FROM Account LIMIT 1];  
 String tPrefix = ObjId.subString(0,3);  
 //Get the Sobject Type  
 String objectType = keyPrefixMap.get(tPrefix);  
                                                                                                                            *above code is no longer needed



But with arrival of Winter 13 / 26.0 API you can directly get the Sobject Type By calling the "getSObjectType()" method.


/*IMPORTANT : replace "sObjId" with your sobject Id, you need not to query the record again,   
 just use the Id field from your record set/ record*/  
 Id sObjId = [SELECT Id FROM Account LIMIT 1].Id;  
 Schema.SObjectType token = sObjId.getSObjectType();  


This new method will be really helpful in writing dynamic apex code for triggers and batches and even for visualforce controllers.


Monday, November 12, 2012


Well someday back, while writing a Visualforce page I came across a situation where I have to convert a string to Id. I tried to check methods for "Id" but couldn't find any thing well after lot tries I actually figured out a way to convert "string" to "Id".

It is super easy, you just need to follow the following code :


 String strId = 'a08A000000ZdZYk';  
 Id myId = strId;  


Hope this helps.

Wednesday, November 7, 2012


[Live Demo]



Please Note : A Newer Version of this Package is available here http://blogforce9.blogspot.in/2013/10/auto-complete-visualforce-component-v2.html


Well working with visualforce pages, I was always tempted to replace the boring lookup field with a autocomplete component which searches the records as we enter text in them. 

So I sat done and wrote a component for my visualforce pages to replace the boring lookup fields dialogs with autocomplete component.


Few features of the autocomplete component
  • Uses Jquery UI to create the autocomplete component.
  • Look And Feel - Has exactly same look and feel as native components
  • Uses Js Remoting to populate data and hence the component is very fast and light weight.
  • Configurable : The search field can be configured to search fields other than "Name" field. Even the value that is returned to controller can be configured return fields other than record Id.
How to use the component in you Visualforce page?


<c:Autocomplete labelField="Name" valueField="Id" SObject="Contact" targetField="{!targetFieldCon}" /> 

Description
  • labelField : The field which is displayed in the component  and against which matching is done with the entered text. In above code snippet Name is displayed in the autocomplete component.
  • valueField : The field value which is passed back to targetfield when a record is selected.
  • targetField : The field from controller where the selected values is set.
  • SObject : The sobject Api Name against which matching/query is done.
For demo purpose you can check the "autocomplete" vf page that is included in package. This page demonstrates the use of the autocomplete component for different sObjects.

Screen : 




Please Note : A Newer Version of this Package is available here http://blogforce9.blogspot.in/2013/10/auto-complete-visualforce-component-v2.html
Package Link :http://blogforce9dev-developer-edition.ap1.force.com/ProjectDetail?id=a0290000007rf2z

Monday, October 15, 2012



As Salesforce is becoming more and more advanced with every release we developer are trying to cope up with the new features released.
Salesforce are releasing awesome features with every release. One of the most remarkable feature is fieldsets.

Fieldsets takes away the most annoying problem of visualforce pages i.e. it makes the pages dynamic!!. Yes Dynamic. The let of configure the fields that
appear in your visualforce page.

How to use fieldsets in your visualforce page.??

<apex:page controller="AccountCon">  
   <apex:form>  
     <apex:pageblock>  
       <apex:pageblocksection columns="1">  
         <apex:repeat value="{!$ObjectType.Account.FieldSets.AccountFieldSet}" var="f">  
             <apex:inputfield value="{!accObj[f]}">  
         </apex:inputfield>  
       </apex:repeat>  
     </apex:pageblocksection>  
   </apex:pageblock>  
  </apex:form>  
 </apex:page>  

public class AccountCon(){  
  public Account accObj{get;set;}  
  public AccountCon(){  
  accObj = [SELECT id,Name FROM Account LIMIT 1];  
  }  
 }  


Well easy enough?
But there lies a problem with fieldsets. In the above example you can see that a static query brings out data from salesforce objects. It will work
just perfect, until and unless some new field that is not included in query is introduced in the query. Once such field is included the code will throw an
exception.

Solution??
Make your query as dynamic as fieldsets!!
To do this I have devised a util class that dynamically generates query using fieldset/fieldsets. Just pass the object name and fieldset name this
will generate a dynamic query according to the parameters passed. Use the returned string to query the data.

Show Me The Code!!
Below is the util class that can be used to generate dynamic query from fieldsets.


 /*  
 *This Class contains utility methods that are used by different classes  
 *in the Org  
 **/  
 public class AVCommonUtils{  
   Map<String, Schema.SObjectType> globalDescribe;   
   public AvCommonUtils(){  
     globalDescribe=Schema.getGlobalDescribe();  
   }  
   /*This method return queries form a single fieldset  
   public String generateQueryFromFieldSet(String sObjectName,String fieldSet,Set<String> additionalFields,String whereClause){  
     return generateQueryFromFieldSets(sObjectName,new Set<String>{fieldSet},additionalFields,whereClause);   
   }  
   /*  
   *This method generates query according to passed in object and fieldsets(plural) name  
   **/  
   public String generateQueryFromFieldSets(String sObjectName,Set<String> fieldSets,Set<String> additionalFields,String whereClause){  
     Set<String> fields = new Set<String>{'Id'};  
     String query='SELECT Id';  //initial query  
     if(additionalFields!=null)  
     for( String fs : additionalFields ) {            
       //add only unique fields  
       if(!fields.contains(fs)){  
         //maintain a set of fields so that only unique fields are added in query  
         fields.add(fs);  
         query = query+','+fs;  
       }      
     }  
     //describe the provided sObject  
     Schema.DescribeSObjectResult res=globalDescribe.get(sObjectName).getDescribe();  
     //get the fields set map  
     Map<String, Schema.FieldSet> fieldSetMap= res.fieldSets.getMap();  
     //iterate through provided fieldsets and generate query  
     for(String fieldSetName : fieldSets){  
       Schema.FieldSet fs = fieldSetMap.get(fieldSetName);  
       for( Schema.FieldSetMember fsm : fs.getFields() ) {            
         //add only unique fields  
         if(!fields.contains(fsm.getFieldPath())){  
           //maintain a set of fields so that only unique fields are added in query  
           fields.add(fsm.getFieldPath());  
           query = query+','+fsm.getFieldPath();  
         }      
       }  
     }  
     query = (whereClause == '' || whereClause ==null)   
             ? (query + ' FROM '+sObjectName)   
             : (query + ' FROM '+sObjectName + ' WHERE ' + whereClause);  
     return query;  
   }  
 }  


How to use the util class??
Let us rewrite the above controller "AccountCon" using the util class.

 public class AccountCon(){   
  public Account accObj{get;set;}   
  public AccountCon(){   
      AVCommonUtils util = new AVCommonUtils();  
      String query = util.generateQueryFromFieldSet('Account','AccountFieldSet',null,'LIMIT 1');  
       accObj = database.query(query);    
  }   
  }   


Well the util classs has two methods.

  1. generateQueryFromFieldSet : This method generates query from only one fieldset
  2. generateQueryFromFieldSets: This method takes in a set of fieldset name to generate query.



Monday, September 10, 2012




In Earlier post "Using Variables In Dynamic SOQL",  I wrote about how to use variables in a Dynamic SOQL. Well after playing with Dynamic SOQL, I found few interesting thing like:

·         You CAN directly use primitive data types in SOQL.

So what does this means?
This means you can directly use any Integer, String , Date, Datetime,Double, Id variable along with Collection of this variable within the query.

For Example: 

a) You are allowed to do this
//initialize the Datetime with current time
DateTime now = System.now();
//query accounts by merging the variable name inside the query string
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE CreatedDate =:now');

b)You can also include LISTs(Collections) in your queries
List<String> accNameList = new List<String>{'Acc1','Acc2'}
//query accounts by merging the variable name inside the query string
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE Name IN:accNameList');


·         You CANNOT use complex types in a Dynamic SOQL directly.
This means that you cannot use any Sobject, Apex Class or Any other user defined data type inside the Dynamic Query. In short you cannot use a dot (".") operator to specify a field value in a Dynamic query.

For Example :

                a)  Using an Sobject inside the query String will not work
           //initialize a Account with a Name value for demo
Account acc = new Account(Name='MyAccount');
//query accounts by merging the variable name inside the query string
//This will not work
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE Name =:acc.Name');

//But You can always make the above work by writing the code as.

           //initialize a Account with a Name value for demo
      Account acc = new Account(Name='MyAccount');
      String accountName = acc.Name
      //query accounts by merging the variable name inside the query string
      List<Account> accountList = Database.query('SELECT Id FROM Account WHERE                       
      Name =: accountName  ');


Hope this helps!.





Saturday, September 8, 2012



10-Sep-2013 : Have a look at my MapMyObject Component, A very flexible Google Map Mapping component.

This is one of the most frequently asked question "How to integrate Salesforce with Google Maps?"
What if you want to show the address of a Say "Account" in the account detail page?
Well the solution is create a inline visualforce page for account and call the google geocoding service to geocode the address ,use that location to mark a point on the map.

Sounds difficult right?
Well in reality its very easy. Just some fancy Java script calls and its done.
Just see the below visualforce page which pulls the Billing Address from the account and displays the same, this page can be included in the Account detail page layout.

Features

  • Shows the Billing Address of the Account in the map
  • On click of the marker a info window is shown with the formatted address.

 <apex:page standardController="Account">  
   <!-- Import Necessary Jquery js File and StyleSheets-->  
   <apex:includeScript value="https://maps.googleapis.com/maps/api/js?sensor=false"/>  
   <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-1.6.2.min.js')}"/>  
   <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-ui-1.8.16.custom.min.js')}"/>  
   <apex:includeScript value="{!URLFOR($Resource.jqPlugin, '/jquery.blockUI.js')}"/>  
   <apex:stylesheet value="{!URLFOR($Resource.jQuery, 'css/ui-lightness/jquery-ui-1.8.16.custom.css')}"/>  
   <script>  
      var map,geocoder,infowindow;  
      var latLngs = [];  
      $j = jQuery.noConflict();   
      $j(document).ready(function(){  
        initialize();  
      });  
      function initialize() {  
       geocoder = new google.maps.Geocoder();  
       //initial cordinates for map init  
       var latlng = new google.maps.LatLng(37.09024, -95.712891);  
       var myOptions = {  
         zoom: 4,  
         center: latlng,  
         mapTypeId: google.maps.MapTypeId.ROADMAP  
       };  
       //load the map  
       map = new google.maps.Map($j('#map')[0], myOptions);  
       codeAddress();  
      }  
      /*This function codes the address using the Billing Address in the Acoount*/  
      function codeAddress(){  
        //prepare a string for geocoding  
        var address = '{!Account.BillingStreet},{!Account.BillingCity},{!Account.BillingCountry},{!Account.BillingPostalCode}';  
        console.log(address);  
        //geocode the address  
        geocoder.geocode( { 'address': address }, function(results, status) {  
          //if it is a success  
          if (status == google.maps.GeocoderStatus.OK) {  
            var location = results[0].geometry.location;  
            var marker=addMarker(location );  
            //attach info window to the marker  
            attachInfoWindow(marker,results[0]);  
          }  
          else {  
            alert(status);  
          }  
        });   
      }  
      /*  
      *This method adds a marker to the provided location  
      **/  
      function addMarker(location) {  
       marker = new google.maps.Marker({  
           position: location,  
           map: map  
         });  
         //set the bounds and initial zoom  
       var latlngbounds = new google.maps.LatLngBounds();  
       latlngbounds.extend(marker.getPosition());  
       map.fitBounds(latlngbounds);  
       map.setZoom(14);  
       return marker;  
      }  
     //this function shows the address of a marker when it is clicked  
     function attachInfoWindow(marker,address){  
        google.maps.event.addListener(marker, 'click', function() {  
          if(infowindow!=null)  
           {  
             infowindow.close();  
           }  
         //HTML formated string that is used to dispaly info window over the map markers currently showing the formated address  
         var contentString = '<div class=" ui-state-active ui-corner-top" style="font-size: 1em; padding: 5px;">Address</div>'  
                   +'<div class="ui-widget-content ui-corner-bottom" style="font-size: .9em; padding: 15px;">'+address.formatted_address+'</div>';  
         infowindow = new google.maps.InfoWindow({  
           content: contentString  
         });  
          infowindow.open(map,marker);  
        });  
     }  
   </script>  
   <style>  
     #map {  
       width:100%;  
       height:200px;   
       margin-left:1.5%;  
     }  
   </style>  
   <div id="map" class="ui-widget-content ui-corner-all ui-state-default"></div>  
 </apex:page>  


How the page looks like?


Page showing the Location of Account


The info window showing the address

Package/Installation
You can use this package to install the same in your org 
https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000M5aT
The above package contains a page called LocateAccount that can be used inline in the Account detail page to display the location or you can pass the Id of account to the page like this /apex/LocateAccount?id=<ACCOUNT ID>".


Thursday, August 23, 2012



This Version is no more actively developed and is deprecated. But we have developed two more Alternatives for the same which are much more fun and easy to implement






This is minor change to my Sortable Pageblock Table Component. This change adds some cosmetic changes like the "legendary" up and down arrow to so the direction of sorting.

If you haven't read about this component earlier you can always have a quick glance to my earlier post here .
(You can find details about implementing in the blog)

Demo
You can check the live demo from here(http://blogforce9dev-developer-edition.ap1.force.com/SortablePageblocktable)

Give the Code:
Well you can install the package from here (https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000M3ie)

Screens.




Sunday, August 19, 2012



Well today while trying to retrieve the label of a field dynamically I found a hidden capability of visualforce!
It not only can retrieve the "label" but almost everything that can be retrieved using "DescribeSObjectResult" and "DescribeFieldResult" .

Instead of rushing into the topic proceed step by step.

Example : Dynamically retrieving the label of Account say phone.
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.label}"/> 

Well we can also retrieve the API name of the field by just changing the "label" with "name"
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.name}"/> 


Well thats not all you can also get the datatype of the field
<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.type}"/> 

So what we are actually doing here?
Well if we simply write "$ObjectType.Account.fields.Phone" we are actually describing the phone field which is equivalent to "Schema.DescribeFieldResult" now if you see the salesforce doumentation for "Schema.DescribeFieldResult"(http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_fields_describe.htm). Now if you see the above page there are lots of methods defined like say  "getLength()" you can simple access the value by dropping the "get" and writing :

<apex:outputLabel value="{!$ObjectType.Account.fields.Phone.length}"/> 

How to do this dynamically?

<apex:outputLabel value="{!$ObjectType.Account.fields[fieldName].label}"/> 


Where "fieldName" is the fieldApi Name.

What else we can do?
Well if you check this page (http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_describesobjects_describesobjectresult.htm) you can almost call every method described in this page. Doing "$ObjectType.Account" actually describes the Account object and now after describing the object you can call almost any of the above methods described in salesforce documentation for "DescribeSObjectResult".

Example 1: Say if I want to retrieve the plural label for sObject "Account" my VF code will be

<apex:outputLabel value="{!$ObjectType.Account.labelPlural}"/>


Example 2 : If I want retrieve the "keyPrefix"

<apex:outputLabel value="{!$ObjectType.Account.keyPrefix}"/>

Like this we can almost get all the properties for a object describe



Friday, August 17, 2012


Well how many times you have tried to use a list variable in a Dynamic SOQL?
We generally use Database.query() ,  which takes a query in string format and returns a List of sObject . The problem comes when want to use "IN" statement or want to use "date/date time" in a Dynamic query . I really tried a lot of combination, formatting the data,escapes etc.But finally was surprised to see if you just include the variable inside the query String, it just works !!!

Wasn't clear enough??

See the below example  which shows how to query all the accounts that are created today:

 
//initialize the Datetime with current time
DateTime now = System.now(); 
//query accounts by merging the variable name inside the query string 
List<Account> accountList = Database.query('SELECT Id FROM Account WHERE CreatedDate =:now'); 




Please Note :  that the variable "now" is included in the string itself.






Monday, August 13, 2012


This Version is no more actively developed and is deprecated. But we have developed two more Alternatives for the same which are much more fun and easy to implement





How many times you have tried to create a Sort-able Page block table?
Well I personally tried the same lot of time but never got a plug n play solution, this always ended up with lots of changes in my controller class.

There are lot of work around Dynamic SOQL,Order by statement, List Sorting etc. Well most of them requires a lot of coding and changes in the visualforce page.
Most of time we need to display just a small list of sortable data ,to implement the same I guess writing apex classes and code is not a good idea.
So I tried writing visualforce component which uses jQuery table sorter to do the job.Well this component is very naive stage and needs some obvious enhancement like, ability to specify which fields to sort, proper images to display the sorting order.

How to use the component?

Parameters
sObjList : List of sObject To display
fieldList : List of field API names to display in the table as column. 

 <c:SortablePageBlockTable sObjList="{!accounts}" fieldList="{!fields}"/>                   



This Version is no more actively developed and is deprecated. But we have developed two more Alternatives for the same which are much more fun and easy to implement






Demo.

You can check the live demo from here(http://blogforce9dev-developer-edition.ap1.force.com/SortablePageblocktable)

Package/Installation
You can use this package to install the same in your org https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000M3iZ

Saturday, June 30, 2012


Well for developing a shiny  Visualforce  page or Image formula, sometimes you may need Icons.
If you look into standard pages, Salesforce uses a very large set of Icons in the standard pages.When you open a standard Case page you can see a "Brief Case" icon at the top of page or when you open a Account you can see a "Folder" icon at the top of the page.

To use these icons I generally look into the standard pages source to extract the exact URL of the icons and then reference them from Visualforce pages. Well that is really hectic. So ease the process I have included them all in Visualforce page and hosted the same.

http://blogforce9dev-developer-edition.ap1.force.com/salesforceicons


To use a icon just click on the icon and the image URL along the image tag will be populated in the footer text box.



Wednesday, June 13, 2012


[Update : Added Live Demo Links]

In the first part I already described you how to create your own wait/loading screen by blocking the full page.(In case you have missed the first part, you can quickly catch up by reading this blog )

Well what if you want to block specific part of the page ?? Like a pageblock or certain set of fields?? Well jQuery is again here to rescue! The good part of jQuery is it mixes with visualforce very readily to give out awesome results!

So lets see how to make this work using the good old jQuery UI Block Plugin.


 How to block a certain portion of page?

 For demo let us assume that we want to block a pageblock while a ajax request is in progress. To achieve this just give page block a unique id say "pb2Block" and use the same from the jquery ui block. Pass in the id of the pageblock which you want to block to the function, probably from a <apex:actionStatus> like this

Action Status
<apex:actionStatus onstart="blockElement('pb2Block')" onstop="unblockElement('pb2Block')" id="blockElement"/>

Command Button

<apex:commandButton value="Send Request" action="{!processAjaxRequest}" reRender="pb" status="blockElement"/>  

so whenever a ajax request is invoked by a command button the onstart event of the actionStatus is fired which blocks the the pageblock with id "pb2Block" and when the ajax request ends the ontstop event is fired which unblocks the pageblock.


 The JavaScript Functions : The demo visualforce page includes two Javascript function to block and unblock the element

              a) blockElement - takes the Salesforce id of the component to block.
              b)unblockElement - takes the Salesforce id of the component to unblock.



How the Page will look like?


Where is the Code?

Visualforce Page
 <apex:page controller="jQueryUIElementBlockDemo_Con">  
   <!-- Import Necessary Jquery js File and StyleSheets-->  
   <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-1.6.2.min.js')}"/>  
   <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-ui-1.8.16.custom.min.js')}"/>  
   <apex:includeScript value="{!URLFOR($Resource.jqPlugin, '/jquery.blockUI.js')}"/>  
   <apex:stylesheet value="{!URLFOR($Resource.jQuery, 'css/ui-lightness/jquery-ui-1.8.16.custom.css')}"/>  
   <script>  
     $j = jQuery.noConflict();  
     /*  
     *Pass the Id of the element to block   
     **/  
     function blockElement(sfId){   
       $j('[id$='+sfId+']').block({ message: '<img src="/img/loading32.gif" /><h1> Loading...</h1>',   
         css: {   
            border: 'none',   
            padding: '15px',   
            '-webkit-border-radius': '10px',   
            '-moz-border-radius': '10px',   
            opacity: .9  
         }   
       });   
       return false;  
     }  
     /*  
     *Pass the Id of the element to unblock   
     **/  
     function unblockElement(sfId){  
       $j('[id$='+sfId+']').unblock();  
     }  
   </script>  
   <apex:form >  
     <!--In the on start event of action status just call the blockPage method and onstop call the unblockPage js method-->  
     <!--Calling the blockElement js function blocks the page until unblockElement method is called-->  
     <!--Please note that the "Id" of element to black is passed to the js functions--->  
     <apex:actionStatus onstart="blockElement('pb2Block')" onstop="unblockElement('pb2Block')" id="blockElement"/>  
     <apex:sectionHeader title="jQuery UI Element Block Demo" subtitle="This is a demo of jQuery UI block for Blocking Certain portion of a page."/>  
     <apex:pageBlock title="Block This Section" id="pb2Block">  
       <apex:pageBlockSection title="Press the send request button to send a ajax request to the controller/server." collapsible="false">  
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Name</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>  
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Phone</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>   
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Mobile</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>  
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Zipcode</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>     
       </apex:pageBlockSection>  
       <apex:pageBlockButtons id="pb">  
         <!--Note here in the status attribute of command button the id of action status is provided-->  
         <apex:commandButton value="Send Request" action="{!processAjaxRequest}" reRender="pb" status="blockElement"/>  
       </apex:pageBlockButtons>  
     </apex:pageBlock>  
     <apex:pageBlock title="Unblocked Section">  
       <apex:pageBlockSection title="This Page block will remain unblocked" collapsible="false">  
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Name</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>  
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Phone</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>   
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Mobile</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>  
         <apex:pageBlockSectionItem >      
           <apex:outputLabel >Zipcode</apex:outputLabel>  
           <apex:inputText />   
         </apex:pageBlockSectionItem>     
       </apex:pageBlockSection>  
     </apex:pageBlock>  
   </apex:form>  
 </apex:page>  


Apex Controller
public class jQueryUIElementBlockDemo_Con {  
   public void processAjaxRequest(){  
     //Do some processing here  
     for(Integer i =0 ; i < 150000; i++){  
     }  
   }  
   //test method  
   static testMethod void test_ProcessAjaxRequest(){  
     new jQueryUIElementBlockDemo_Con().processAjaxRequest();  
   }  
 }  

Demo

Need more help to implement?

Don't worry packaged a demo visualforce page and all the necessary static resources like jQuery files, jQuery UI Block Plugin. Install the demo page from the here http://blogforce9dev-developer-edition.ap1.force.com/ProjectDetail?id=a0290000007rfwN




Saturday, June 9, 2012



[Update : Added Live Demo Links]

Ever wondered how to show user a wait or loading message while a ajax call from a visualforce page is in progress?
Well the answer is yes! You can always show a message to user using action status.
What if you want to block the page or some predefined area? Well the solution is jQuery UI block. Using this plugin you can actually block portions of visualforce page while the ajax action is processing.Well the part 1 I am demonstrating how to block the full page while a ajax request is in progress.

How it works?

Very simple from <apex:commandButton/> or <apex:actionFunction/> simply relate a <apex:actionstatus/> component which has a "onstart" and "onstop" event. Call the "blockPage" js function from the "onstart" and call "unblockPage" function from "onstop" attribute.

How the Page will look like?




Visualforce Page


<apex:page controller="jQueryUIBlockDemo_Con">  
   <!-- Import Necessary Jquery js File and StyleSheets-->  
   <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-1.6.2.min.js')}"/>  
   <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-ui-1.8.16.custom.min.js')}"/>  
   <apex:includeScript value="{!URLFOR($Resource.jqPlugin, '/jquery.blockUI.js')}"/>  
   <apex:stylesheet value="{!URLFOR($Resource.jQuery, 'css/ui-lightness/jquery-ui-1.8.16.custom.css')}"/>  
   <script>  
     $j = jQuery.noConflict();  
     //function to block the whole page  
     function blockPage(){   
       $j.blockUI({ message: '<img src="/img/loading32.gif" /><h1> Loading...</h1>',   
         css: {   
          border: 'none',   
          padding: '15px',   
          '-webkit-border-radius': '10px',   
          '-moz-border-radius': '10px',   
          opacity: .9  
         }   
       });   
       return false;  
     }  
     //function to unblock the page  
     function unblockPage(){  
       $j.unblockUI();  
     }  
   </script>  
   <apex:form >  
     <apex:sectionHeader title="Jquery UI Block Demo" subtitle="This is a demo of jQuery UI block for Blocking the whole page when a ajax request is in progress!"/>  
     <!--In the on start event of action status just call the blockPage method and onstop call the unblockPage js method-->  
     <!--Calling the blockPage js function blocks the page until unblockPage method is called-->  
     <apex:actionStatus onstart="blockPage()" onstop="unblockPage()" id="blockUI"/>  
     <apex:pageBlock title="Jquery UI Block Demo">  
       <p>Press the send request button to send a ajax request to the controller/server.</p>  
       <apex:pageBlockButtons id="pb">  
         <!--Note here in the status attribute of command button the id of action status is provided-->  
         <apex:commandButton value="Send Request" action="{!processAjaxRequest}" reRender="pb" status="blockUI"/>  
       </apex:pageBlockButtons>  
     </apex:pageBlock>  
   </apex:form>  
 </apex:page>  


Apex Controller


 public class jQueryUIBlockDemo_Con{  
   public void processAjaxRequest(){  
     //Do some processing here  
     for(Integer i =0 ; i < 10000; i++){  
     }  
   }  
   //test method  
   static testMethod void test_ProcessAjaxRequest(){  
     new jQueryUIBlockDemo_Con().processAjaxRequest();  
   }  
 }  

Demo
You can check the live demo from http://blogforce9dev-developer-edition.ap1.force.com/jQueryUIBlockDemo

Need more help to implement?

Don't worry packaged a demo visualforce page and all the necessary static resources like jQuery files, jQuery UI Block Plugin. Install the demo page from the the Project Detail Page http://blogforce9dev-developer-edition.ap1.force.com/ProjectDetail?id=a0290000007rfwI and go to "jQueryUIBlockDemo". The code is well commented and ready to use.

Thursday, May 24, 2012



[You can see this blog for a more elegant solution ]

This was unknown to me and in past months I tried hard to use Datetime field in Dynamic SOQL query, well after doing lots of permutations and combinations I finally figured it out! which I though was not possible.

Well I guess this is worth sharing so here it is.

You can compare any Datetime field in Dynamic SOQL where query! Just keep in mind the format should be correct. You can use the format method to format datetime field like this where System.Now() is my Datetime field.

System.Now().format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''));


OR




DateTime dt = System.Now();//initialize datetime with current datetime

String formatedDt = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');//format the datetime to make it Dynamic Soql ready


So a sample query to extract all the Accounts where the CreatedDate is less than Today will be


DateTime dt = System.Now();//initialize datetime with current datetime
String formatedDt = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');//format the datetime to make it Dynamic Soql ready
Database.query('Select Id FROM Account WHERE CreatedDate<'+formatedDt);



Wednesday, May 23, 2012


Well Summer 12 is approaching with lots of new enhancements including fieldset describing feature from within apex.This was most awaited feature for me because have done a lot work around to achieve the same result.
Thanks to Abhinav Gupta from whose blog(http://www.tgerm.com/2012/01/recordtype-specific-picklist-values.html) I actually got Idea how to develop these feature. Sometime back Abhinav wrote about describing picklist based on recordtype, I took the code from there and made some changes in the classes and Eureka! a fieldset describer is at your service.

Well since Summer 12 is approaching very fast and after that this will not be of any use,So this for those user who are still stuck in Spring 12 and need a work round to get a List of field names that a field set contains. Well you can install the package from this link https://login.salesforce.com/packaging/installPackage.apexp?p0=04t900000009eGV

It mainly contains two classes. A visulaforce controller to generate a page using the fieldset and parsing the response and another main class to which we send Field Set name and Object name.

How to describe a fieldset?
Its very easy just follow the below code.

List<String> fieldNameList = FieldSetDescriber.describeFieldSet('<Your Object Name>','<Your Field Set Name>');



Tuesday, May 22, 2012


Well few days ago I came across a requirement where on button click user should be asked for confirmation about the action in a modal window. Well we don't have such component in Visualforce!. But hey! Wait! I guess the jquery has it! Why dont we use that one ?

So started mixing Visualforce with Jquery and Result? A modal dialog box!


Well Don get scared its very easy to implement!

Just go to apex/showDialog page for demo and press the showDialog button.

To summarize you can just open a modal window by just calling the openDialog method included in the showDialog page,make sure that you include necessary files while you implement the same in your VF page.

Exp : openDialog('This is a custom dialog','Alert')" ;
Where the first argument is the dialog body and the second is the Dialog title.

Thursday, February 2, 2012


[Update:Added Live Demo Link And Unmanaged package Link]

Talking about the Visualforce component , It has all the component that can make a decent UI but its only limited to the word "DECENT", you can create very rich UI using visualforce.What if  a simple slider needs to be implemented in a Visualforce page? Alas! there are no such component in the standard Visualforce Library.

Well you can create one for yourself using jQuery Library. Talking about jQuery its very stable javascript library with lots of feature! It Readily mixes with visualforce to create very rich UI.

So lets have look on the code to create a simple slider using jQuery.

Visualforce Page

<apex:page controller="jqSlider_Con">  
      <!--Inculding the required jQuery Files and CSS--->  
      <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-1.6.2.min.js')}"/>  
      <apex:includeScript value="{!URLFOR($Resource.jQuery, 'js/jquery-ui-1.8.16.custom.min.js')}"/>  
      <apex:stylesheet value="{!URLFOR($Resource.jQuery, 'css/ui-lightness/jquery-ui-1.8.16.custom.css')}"/>  
      <script>  
        $j = jQuery.noConflict();   
        //this function will be called as soon as page load is complete  
        $j(function(){  
          //calling the createSlider Method to create the slider in designated location  
          createSlider('slider','disp','idInputHidden',0,0,1000);  
       });  
        /*  ----------------------------  
        *  Method to create the Slider  
        *  ----------------------------  
        *  PARAMETERS : "destination" = The Id of the div where the slider needs to be created  
        *         "dispOutput" = The Id of the div where the slider value needs to be displayed  
        *         "idInputHidden" = The Id of the apex inputHidden component  
        *         "startVal" = initial position of slider  
        *         "minVal", "maxVal" = minimum and maximum value of slider  
        **/  
         function createSlider(destination,dispOutput,idInputHidden,startVal,minVal,maxVal){  
           $j("#"+destination).slider({   
             range: false,   
             min: minVal,  
             max: maxVal,  
             values: [startVal],  
             slide: function(event, ui){   
             //This function executes every time slider is moved and applies the slider values   
             //to the input fields as well as the output below the slider  
               $j("[id$="+idInputHidden+"]").val(ui.values[0]);  
               $j("#"+dispOutput).html('$' + ui.values[0]);  
             }  
           });  
           //write the initial value in the display div  
           $j("#"+dispOutput).html('$' + startVal);  
         }   
     </script>  
     <apex:form >  
       <apex:pageBlock title="jQuery Slider">  
         <!--Slider will be created Here-->  
         <div id="slider"/><br/>  
         <!--Slider Output here-->  
         <div id="disp"/>  
         <apex:inputHidden value="{!sSliderField}" id="idInputHidden"/>  
         <apex:pageBlockButtons >  
           <apex:commandButton value="Submit" action="{!checkSliderVal}" reRender="idInputHidden"/>  
         </apex:pageBlockButtons>  
       </apex:pageBlock>  
     </apex:form>  
  </apex:page>  

Controller Class

 public class jqSlider_Con {  
     public String sSliderField { get; set; }  
     public void checkSliderVal(){  
       System.debug('###-------------+'+sSliderField );  
     }  
  }  


About the method "createSlider": In this example I have created a function "createSlider". Which takes in the id of div where the slider neds to be rendered, the id of div where the the values should be displayed, the id of the apex inputHidden(so that values can be passed to controller), the initial value of the slider and range of the slider(max and minimum value).This method can be called multiple times for creating slider in different location of page.




Passing Values to Controller: The values are passed to controller using apex inputHiddent element which assigns the value to a public variable. You can check the communication by clicking the submit button, the value of the slider will assigned to the sSliderField and can be seen in debug logs.


Demo

You can check the live demo by going to 
http://blogforce9dev-developer-edition.ap1.force.com/jQSlider


Package For Installation

Install the demo in your developer Org by using this url : 
https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000LxdC