October 4, 2010

Playing with Visualforce $Action Global Variable

Recently, I stumbled upon Visualforce $Action tag. My requirement was :

  • To open the standard “List” page of an Sobject from Visualforce page.
  • To open “New” Contact page from Visualforce page.

Seems too simple :)

I know $Action tag was the way, so I jumped to the “Visualforce docs for Global Variables”. But can’t find any good code sample at this page, only one sample that’s available is for opening new Account page ($Action.Account.New). So I started searching for some sample with Visualforce documentation, found a couple of good links like :

Still I was struggling to open “New” Contact page, based on what I understood from Account code sample in “Visualforce docs for Global Variables”.  I was trying following code snippet to open it in similar fashion.

<apex:outputLink value="{!URLFOR($Action.Contact.New)}">
    Create New Contact
</apex:outputLink>

This didn’t worked, so have to jump on force.com forums for any solution. Luckily I found this link/solution, it clearly states

“This is the syntax you want: {!URLFOR($Action.Contact.NewContact)}

If you're having problems figuring out the name of an action go to Setup -> Customize -> Contacts -> Buttons and Links and look in the "Name" column for the action you want.

I wish the above solution in green is available in original “Visualforce docs for Global Variables”. It was so confusing to have different Action names for even standard objects like Account and Contact.

We need more code samples on $Action

Even after the above solution, I found that every $Action has some dependencies on params etc. For ex.

  • You need to pass in ObjectType with “List” Action : URLFOR($Action.CustomSobject__c.List,  $ObjectType.CustomSobject__c)
  • You need to pass in Object Id to “View” Action : URLFOR($Action.CustomObject__c.View, 'a00900000016iUl')
  • Action to open new Contact is “$Action.Contact.NewContact”, whereas the same for Account is “$Action.Account.New”
  • Similarly, their can be many such examples and special cases.

Lets collect $Action code snippets.. !

Because of many such options with $Action, I thought of creating a centralized collection of all such $Action possibilities & code snippets. This can for sure help other Visualforce developers. For that I started creating some code samples at snipplr.com under tag “visualforce-action-var”.

If you have any more cool samples around $Action, please share on snipplr.com with tag: “visualforce-action-var”.

References