You are on page 1of 7

Javascript with Visualforce pages

Javascript is one of key browser technology on Visualforce pages. Javascript provides the framework for communication between other Javascript objects, HTML elements and visualforce controller. This example will explain how can we use javascripts in visualforce pages.
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

<apex:page> <script> function changeFont(input, textid) { if(input.checked) document.getElementById(textid).style.fontWeight = "bold"; else document.getElementById(textid).style.fontWeight = "normal"; } </script>

<apex:outputPanel layout="block"> <label for="checkbox">Click this box to change text font: </label> <input id="checkbox" type="checkbox" onclick="changeFont(this,'{!$Component.thePanel}');"/> </apex:outputPanel> <apex:outputPanel id="thePanel" layout="block">Change me! </apex:outputPanel> </apex:page>

'{!$Component.idName}' : This is the way of passing particular visualforce component id into the javascript

Javascript Remoting for APEX controller


Javascript remoting is the process that provides support for some methods in APEX controllers to be called via Javascript.The @RemoteAction annotation is currently available as a Developer preview.You have to contact Salesforce.com support to enable this feature.To use Javascript remoting, your request must take the following form:
view plaincopy to clipboardprint?

1. 2. 3. 4.

[<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event) { // callback function logic }, {escape:true});

namespace is your organization's namespace. This is only required if the class comes from an installed packaged. controller is the name of your Apex controller method is the name of the Apex method you're calling params is the commaseparated list of parameters that your method takes callbackFunction is the name of the function that handles the response from the controller. It returns the status of the call and the method result. escape defines whether your response should be escaped (by default, true) or not (false) In controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
view plaincopy to clipboardprint?

1. @RemoteAction 2. global static String getItemId(String objectName) { ... }

Example code: /*VF page*/


view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

<script type="text/javascript"> function updateStatus(input,id) { var inputStatus=id; shortList.doShortListThroughCheck(inputStatus,function(result,event){ if(input.checked){ document.getElementById(id).value="Short Listed"; alert(document.getElementById(id).value); }else{ document.getElementById(id).value="New"; alert(document.getElementById(id).value); } },{escape:true}); }</script>

/*@VF Component*/
view plaincopy to clipboardprint?

1. <apex:selectCheckboxes onclick="updateStatus(this,'{!app.Name}');"> 2. </apex:selectCheckboxes>

/*In Controller*/
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

@RemoteAction global static Applicant__c doShortListThroughCheck(String para){ Applicant__c applicant; try{ applicant=[select Name, Name__c, Status__c from Applicant__c where Name =:para limit 1]; applicant.Status__c='Short Listed'; update applicant; }catch(DMLException e){ ApexPages.addMessages(e); return null; } return null; }

Parameter passing using Javascript+actionFunction in visualforce


In visualforce, there is a method for passing parameters from visualforce page to controller using javascript and actionFunction. Here is the example;
/*JavaScript*/
view plaincopy to clipboardprint?

1. 2. 3. 4. 5.

<script type="text/javascript"> function doSave(date) { paraFunction(document.getElementById(date).value); } </script>

/*Action Function*/
view plaincopy to clipboardprint?

1. <apex:actionFunction name="paraFunction" action="{!saveInterviewDate}" rerender="view"> 2. 3. <apex:param id="aname" name="interviewDate" value="" /> </apex:actionFunction>

/*Call the javaScript from here*/


view plaincopy to clipboardprint?

1. <apex:commandLink onclick="doSave('{!$Component.interviewDate}');"> 2. <apex:commandButton value="Save"/> 3. </apex:commandLink>

/*get the parameter in controller*/

view plaincopy to clipboardprint?

1. String interviewdate=Apexpages.currentPage().getParameters().get('interviewDate');

Inline Editing in Visualforce page

Inline editing in Visualforce was introduced with the Spring'11. It has the ability to turn on inline editing within Visualforce, a handy bit of user friendliness which has been availability in the standard application interfaces for some time. Enabling inline editing is simple. My example is related with the Contact Standard object. But this feature will work with custom objects as well.
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

<apex:page standardController="Contact"> <apex:form > <apex:pageBlock mode="inlineEdit"> <apex:pageBlockButtons > <apex:commandButton action="{!edit}" id="editButton" value="Edit"/> <apex:commandButton action="{!save}" id="saveButton" value="Save"/> <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/> </apex:pageBlockButtons> <apex:pageBlockSection > <apex:outputField value="{!contact.lastname}"> <apex:inlineEditSupport showOnEdit="saveButton, cancelButton" hideOnEdit="editButton" event="ondblclick" changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/> </apex:outputField> <apex:outputField value="{!contact.accountId}"/> <apex:outputField value="{!contact.phone}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

Just copy and paste this code in your visualforce editor. After run it obviously you will not see the values in output fields. Just append the URL with some contact object id as follows. Ex: https://yourOrganizationLink/apex/yourVFPageName?id=someCantactObjectId https://c.ap1.visual.force.com/apex/InlineEditNew?id=00390000005ZFzB

Displaying pop-up summaries on hover in visualforce


What if I want to make a summary pop-up window when a user hovers over a link in a visualforce page. This Feature is easy in standard salesforce pages, mostly because it happens automatically. But not in visualforce pages. I have seen most of example for pop-up in salesforce were created using the output panels with some embedded styles. Here I'm posting a pop-up example which show the details of a partuclar record on a mouseover using the Hover links similar to those used in standard Salesforce links. /*visualforce page*/
view plaincopy to clipboardprint?

1. <apex:page controller="PopupTest"> 2. <apex:form > 3. <apex:repeat value="{!accounts}" var="acc"> 4. 5. <a href="/{!acc.Id}" id="{!acc.Id}" onblur="LookupHoverDetail.getHover('{!acc.Id}').hide(); " onfocus="LookupHoverDetail.getHover('{!acc.Id}', '/{!acc.Id}/m?retURL=%2F{!acc.Id}&isAjaxRe quest=1').show();" onmouseout="LookupHoverDetail.getHover('{!acc.Id}').hide();" onmouseover=" LookupHoverDetail.getHover('{!acc.Id}', '/{!acc.Id}/m?retURL=%2F{!acc.Id}&isAjaxRequest=1').s how();">{!acc.Name}</a> 6. </apex:repeat> 7. </apex:form> 8. </apex:page>

/*Controller*/
view plaincopy to clipboardprint?

1. public with sharing class PopupTest { 2. public List<ACCOUNT> getAccounts() 3. { 4. List<ACCOUNT> accounttList = new List<ACCOUNT>(); 5. accounttList = [Select Id, Name from Account LIMIT 10]; 6. return accounttList ; 7. } 8. 9. } 10. </ACCOUNT></ACCOUNT></ACCOUNT>

Declaration: Directly depending on standard javascript libraries, query params, dom ID values or services (excluding the web services API, of course) is at your own risk. None of which are considered to be supported "APIs" and can change with any major or minor (patch) release without notice. Therefore promote this idea on ideaExchange in salesforce. https://sites.secure.force.com/success/ideaView?c=09a30000000D9xtAAC&id=0873000000 0a53fAAA

Save an attachment in APEX

Attachment field allows users to be able to attach notes and attachments to custom object records. This allows you to attach external documents to any object record, in much the same way that you can add a PDF or photo as an attachment to an email. This option is only available when you are creating a new object. Here I have an example for save an attachment in APEX. /*****Controler*****/
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.

public class status{ private final Applicant__c applicant; public Blob resume {get; set;} public String contentType {get; set;} public String fileName {get; set;} public status(ApexPages.StandardController stdController) { this.applicant=(Applicant__c)stdController.getRecord(); } public PageReference saveApplication() { try{ insert(applicant); }catch(System.DMLException e){ ApexPages.addMessages(e); return null; } if(resume!=null){ Attachment attach=new Attachment(); attach.Body=resume; attach.Name=filename; attach.ContentType=contentType; attach.ParentID=applicant.id; try { insert(attach); } catch(System.DMLException e) { ApexPages.addMessages(e); return null; } } PageReference p = Page.Confirmpage; p.setRedirect(true); return p; } }

/**Controller**/
view plaincopy to clipboardprint?

1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

<apex:page standardController="Applicant__c" extensions="status"> <apex:form > <table> <tr> <td>Applicant Name </td> <td><apex:inputField value="{!Applicant__c.Name__c}"/></td> </tr> <tr> <td>CV </td> <td> <apex:inputFile accept="doc, txt, pdf" filename="{!fileName}" contentType="{!contentType }" filesize="1000" size="50" value="{!resume}"/> </td>

11. 12. 13. 14. 15. 16. 17. 18.

</tr> <tr> <td></td> <td><apex:commandButton id="submitApplicant" value="Submit" action="{!saveApplication}"/></td > </tr> </table> </apex:form> </apex:page>

You can try it with your own object and particular fields.

You might also like