Things to keep in mind while developing the Salesforce App-exchange Application

In this post, I will discuss what are the important parameters that need to be taken care while developing the App-Exchange Application using Salesforce. Before we dive into the concepts I would like to tell you that after developing the application, every application goes with the below security checks

  1. Checkmarx: – It is a free tool available to scan the Complete Code that is in your org where development has been done.
  2. Security Review: – The second step after submitting the code to the checkmarx and resolving all the issues is to Submit the package for the security review where salesforce representatives check the Quality of the code and functionality as well.

So, In order to develop the application which is secure and minimize the risk of data compromise or any other confidential information a developer must need to keep the following points into the mind while developing the application

1Cross-Site Scripting 
2S(O)QL Injection 
3Cross Site Request Forgery 
4Secure Communications and Cookies 
5Storing Secrets 
6Arbitrary Redirects 
7Access Control 
8Lightning Security Best Practices 
9Marketing Cloud App Security
10Secure PostMessage
11Secure WebSockets

Here is a Link to Trailhead module which explains everything about secure coding guidelines with the practical example

https://trailhead.salesforce.com/en/modules/secdev_injection_vulnerabilities/units/secdev_inject_get_started_wappsec

Resources: – 

  1. Salesforce Document
  2. Salesforce Security Guide
  3. An Overview of Force.com Security
Advertisements

How to Call Salesforce API from Lightning Component

You may have heard about that we can not make the Salesforce API Call directly from the lightning component. If you do make the callout from the lightning component then you will get the below error

INVALID_SESSION_ID:This session is not valid for use with the API.

For Example when you will execute the below code from the Developer Console then you will get the Valid Response


HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
HttpResponse resp = new HttpResponse();

req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v41.0/query?q=Select+Id,+Name+From+Account');
resp = h.send(req);
System.debug('#### Response Status '+resp.getStatus());
System.debug('#### Response Status Code '+resp.getStatusCOde());
System.debug(resp.getBody());

But if you will call the same block from the Lightning Component then you will get INVALID_SESSION_ID:This session is not valid for use with the API. Error.

I gone through with this error and found THIS SALESFORCE DOCUMENT where they have specified why we can not make API Call from JavaScript Code.

After reading the document, I have come up with 2 Solutions that are given below: –

1 – Connected App and Named Credentials as Callout Endpoints and Auth Providers

2 – Using VF Page – VF page will be used to get the Session Id of the current log in user and this VF page will be used into Apex class for fetching the Session Id.

In this tutorial we will use VF page for making callout because it is an easy and simple method method. Follow the below steps

Step1 – Open Developer Console, File -> New -> VisualForce Page -> Enter Name “GetSessionIdVF” -> OK. Use below code for VF Page


<apex:page >
 Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>

Step2 – Create a New Class which will use this VF page to get the Session Id and making API Call Out. File -> New -> Apex Class -> Name it “ApiCallLightningComponent” -> OK. Use below code for the class.


public class ApiCallLightningComponent {
 /*
 * @Name : - fetchUserSessionId
 * @Description: - Call the VF page and get the Log In Use Session Id
 * @Params : - none
 * @ReturnType : - String
 */
 public static String fetchUserSessionId(){
 String sessionId = '';
 // Refer to the Page
 PageReference reportPage = Page.GetSessionIdVF;
 // Get the content of the VF page
 String vfContent = reportPage.getContent().toString();
 System.debug('vfContent '+vfContent);
 // Find the position of Start_Of_Session_Id and End_Of_Session_Id
 Integer startP = vfContent.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
 endP = vfContent.indexOf('End_Of_Session_Id');
 // Get the Session Id
 sessionId = vfContent.substring(startP, endP);
 System.debug('sessionId '+sessionId);
 // Return Session Id
 return sessionId;
 }
 /*
 * @Name - makeAPICall
 * @Description - Responsible for making API Call out
 * @params - None
 * @ReturnType - String
 */
 @AuraEnabled
 public static String makeAPICall(){
 String sessionId = fetchUserSessionId();
 HTTP h = new HTTP();
 HTTPRequest req = new HTTPRequest();
 HttpResponse resp = new HttpResponse();
 req.setMethod('GET');
 req.setHeader('Authorization', 'Bearer ' + sessionId);
 req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v41.0/query?q=Select+Id,+Name+From+Account');
 resp = h.send(req);
 System.debug('#### Response Status '+resp.getStatus());
 System.debug('#### Response Status Code '+resp.getStatusCOde());
 System.debug(resp.getBody());
 return JSON.serialize(resp.getBody());
 }
}

See the comments.

ApiCallLightningComponent class contains 2 methods fetchUserSessionId and makeAPICall, One for getting the Session Id and Other for making the Callout that will be called from the JavaScript.

Step3 – Create a lightning component, File -> New -> Lightning Component -> Name it “MakiAPICall” -> OK. Use below code for the Component


<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes, flexipage:availableForRecordHome,force:hasRecordId, forceCommunity:availableForAllPageTypes, force:lightningQuickAction" controller="ApiCallLightningComponent" access="global" >
<div class="slds-m-around_x-small">
			<lightning:button variant="brand" label="Make CallOut" iconName="action:apex" iconPosition="left" onclick="{!c.doHandleClick }" /></div>
</aura:component>

Click on the Controller and use below code


({
doHandleClick : function(component, event, helper) {
helper.onHandleClick(component, event, helper);
}
})

Click on the helper and then use below code for helper


({
onHandleClick : function(component, event, helper) {
// Get the action of Controller (Apex) Class
var action = component.get('c.makeAPICall');

// set the callback which will return the response from apex
action.setCallback(this, function(response){
// get the state
var state = response.getState();
if( (state === 'SUCCESS' || state ==='DRAFT') && component.isValid()){
// get the response
var responseValue = response.getReturnValue();
// Parse the respose
var responseData = JSON.parse(responseValue);
alert(responseData);
//alert(responseData.totalSize);
console.log(responseData);
} else if( state === 'INCOMPLETE'){
console.log("User is offline, device doesn't support drafts.");
} else if( state === 'ERROR'){
console.log('Problem saving record, error: ' +
JSON.stringify(response.getError()));
} else{
console.log('Unknown problem, state: ' + state +
', error: ' + JSON.stringify(response.getError()));
}
});
// send the action to the server which will call the apex and will return the response
$A.enqueueAction(action);
}
})

Step4 – In Final Step Test the Component using Lightning Application. File -> New -> Lightning Application -> Enter Name -> Submit -> Use below Code


<aura:application extends='force:slds' >
<c:MakiAPICall/>
</aura:application>

Note: – If Your component name is different then use the name of your component instead of MakiAPICall.

Output of the above code

Call API From Lightning Component

You can find the complete Here.

Happy Learning 🙂

Happy Coding 😉

Sharing is Caring

Resources –

 

Salesforce – Quickbooks Online Integration – oAuth 2.O

Hi All, Hope you all enjoyed my previous Integration related posts. I have come up with another integration. In this post we will make connection between Salesforce and Quickbook System using Apex, VF page.

Earlier Quickbooks uses oAuth 1.0 for the authentication but now it has updated it’s API and using oAuth 2.0 so in this Integration we are going to use oAuth 2.0

Step1 – Create a Custom Object OR Custom Metadata to store the information about Access and Refresh Token. If you are thinking about to use Custom Setting the answer is No because Access Token length is more than 255 Character and in Custom Setting we can store data upto 255 Character.

Setup -> Create -> Objects -> New -> Your Object will look like below image

QuickBooks Infos Object

Step2 – Create a Trail Account of QuickBooks From Here.

Step3 – Create a connected App into QuickBooks Developer account, Follow the steps given into this Link. Please enter a redirect URI. for example if you want to redirect into “QuickbookConnection” VF page and your org base URL is “https://dreamhouse-a-dev-ed.my.salesforce.com&#8221; then your Redirect URI will be as given below

https://dreamhouse-a-dev-ed–c.ap5.visual.force.com/apex/QuickbookConnection

Step4 – Now, in this Step get the Consumer Secret and Consumer Key and to get the key follow the steps given in This Link.

Connected App

Step5 – Now, Create a Apex Class. File -> New -> Apex Class -> Name it “QuickbookConnection” -> OK. Use below code the class

Step5 – Create a VF page. File -> New -> Visualforce Page -> Name “QuickbookConnection” -> OK. and use below code for this page


&lt;apex:page controller="QuickbookConnection"&gt;
&lt;apex:slds /&gt;
&lt;apex:form id="theForm" &gt;
&lt;apex:pageblock &gt;
&lt;apex:pageMessages &gt;&lt;/apex:pageMessages&gt;
&lt;apex:actionstatus id="statusAuthQuickBooks"&gt;
&lt;apex:facet name="start"&gt;
&lt;div class="waitingSearchDiv" id="el_loading" style="background-color: #fbfbfb; height:100%;opacity:0.65;width:100%;"&gt;
&lt;div class="waitingHolder" style="top: 100px; width: 91px;"&gt;
&lt;img class="waitingImage" src="/img/loading.gif" title="Please Wait..." /&gt;
&lt;span class="waitingDescription"&gt;Loading...&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/apex:facet&gt;
&lt;/apex:actionstatus&gt;
&lt;apex:pageBlockButtons location="top"&gt;
&lt;apex:commandButton action="{!doAuthorizationQuickBooks}" value="Authorize with Quickbooks" /&gt;
&lt;apex:commandButton action="{!doFetchAccessToken}" value="Complete Authorzation" status="statusAuthQuickBooks"
reRender="theForm" /&gt;
&lt;/apex:pageBlockButtons&gt;
&lt;/apex:pageblock&gt;
&lt;/apex:form&gt;
&lt;/apex:page&gt;

tada we have done with the coding and configuration part, now time to test the functionality. Click preview on the VF page. Click on Authorize with QuickBooks it will take you to login page of QuickBooks login with your username and password.

If you have more than 1 Sandbox it will list all the sandbox over there select one which you want to integrate.

Authorize the Application and you will be redirected to the same page now click on Complete Authorization it will create a record for the custom Object that you have created with success message

See the working in below gif Image

Salesforce - Quickbooks Working.gif

Now, We have access token we can make the callout to get the data from QuickBooks into Salesforce. You can find the complete code form Here.

If you have any problem then please come up into comment section.

Happy Learning 🙂 😉

Resources –

Top 10 Features for Lightning Development – Spring 18 Release

New Lightning Components

Note: – The following components are new and require API version 42.0 and later.

  • lightning:carousel (Beta): – A collection of images that are displayed horizontally one at a time. As this is a beta version feature it will have some limitations.

base_carousel

  • lightning:formattedAddress: – Displays a formatted address that provides a link to the given location on Google Maps.

base_formattedAddress

  • lightning:inputAddress: – Input fields represents an address compound field with support for street, city, province, postal code, and country.

base_inputAddress.png

  • lightning:inputField : – An editable field with a label, help text, and value that corresponds to a field on a Salesforce object. This component must be nested in a lightning:recordEditForm component.
  • lightning:inputName: – Represents a name compound field with support for salutation, first name, middle name, last name, informal name, and suffix.

base_inputName.png

  • lightning:listView : – Represents a list view of records that you own or have read or write access to, and records shared with you.

base_listView.png

  • lightning:recordEditForm : – A record edit or record create layout that displays one or more fields provided by lightning:inputField.

base_inputField.png

  • lightningsnapin:prechatAPI : – Enables customization of the user interface for the pre-chat page in Snap-ins Chat.

Changed Lightning Components

lightning:datatable: – Datatable an amazing feature that we got in the previous release (winter 18) has many new features in the coming release Spring 18.

Text wrapping and clipping within a column is now supported. Text wrapping expands the height of the rows to reveal more content. Content is clipped by default if the number of characters is more than what the column width can hold. To toggle between the two views, select Wrap text or Clip text from the dropdown menu on the column header.Other features that are now supported include:

  • Appending icons to the header column
  • Header-level actions
  • Infinite loading of rows
  • Row-level actions
  • Selecting rows programmatically
  • Using a button as a data type

These features are captured by the following lists of attributes, column properties, and data types.

The following attributes are new.

  • enableInfiniteLoading—Enables or disables infinite loading. The default is false.
  • isLoading—Specifies whether more data is being loaded, and displays a spinner if there is. The default is false.
  • loadMoreOffset—Determines when to trigger infinite loading based on how many pixels the table’s scroll position is from the bottom of the table. The default is 20.
  • selectedRows—Enables programmatic row selection with a list of keyField values.
  • maxRowSelection—Maximum number of rows that can be selected. Checkboxes are used for selection by default, and radio buttons are used when maxRowSelection is 1.
  • onheaderaction—The action triggered when a header action is clicked. By default, it also closes the header actions menu.
  • onloadmore—The action triggered when infinite loading loads more data.
  • onresize—The action triggered when the table renders columns each time it resizes a column.
  • onrowaction—The action triggered when a row action is clicked. By default, it also closes the row actions menu.
  • rowNumberOffset—Determines where to start counting the row number. The default is 0.
  • showRowNumberColumn—Shows or hides the row number column. Set to true to show the row number column. The default is false.

The following column properties are new.

  • actions—Appends a dropdown menu of actions to a column.
  • cellAttributes—Provides additional customization, such as appending an icon to the output. You can pass in these attributes: iconName, iconLabel, iconPosition.
  • iconName—The Lightning Design System name of the icon. Names are written in the format standard:opportunity. The icon is appended to the left of the header label.

The following data types are now supported.

  • action—Displays a dropdown menu using lightning:buttonMenu with actions as menu items. This data type supports these typeAttributes properties: rowActions and menuAlignment.
  • button—Displays a button using lightning:button. This data type supports these typeAttributes properties: disabled, iconName, iconPosition, label, name, title, variant.

The url data type now supports the following typeAttributes property.

  • label—The text to display in the link. Give label of the record name or anything you want.

The date type now supports the following typeAttributes properties.

  • day—Valid values are numeric and 2-digit.
  • era—Valid values are narrow, short, and long.
  • hour—Valid values are numeric and 2-digit.
  • hour12—Determines whether the time is displayed as 12-hour. If false, time displays as 24-hour. The default setting is determined by the user’s locale.
  • minute—Valid values are numeric and 2-digit.
  • month—Valid values are 2-digit, narrow, short, and long.
  • second—Valid values are numeric and 2-digit.
  • timeZone—The time zone to use. Implementations can include any time zone listed in the IANA time zone database. The default is the runtime’s default time zone. Use this attribute only if you want to override the default time zone.
  • timeZoneName—Valid values are short and long. For example, the Pacific time zone displays as PST if you use short or Pacific Standard Time if you use long.
  • weekday—Valid values are narrow, short, and long.
  • year—Valid values are numeric and 2-digit.

 

Happy Reading 🙂

You can try all these features into the Sandbox Org once this release has been loaded into Sandbox after 5th Jan OR 6th of Jan 2018.

Resources: –

Salesforce Release Document

 

LinkedIn – Salesforce Integration

Hello All, I am back with another Integration post and in this post, I will show how you can connect with LinkedIn from your salesforce org using a small piece of code.

So, Get ready to do another integration with Salesforce.

Before we start playing with the code we need to create a Custom Setting where we will store Access Token and Expiry time so that we could use this while making the callouts.

Setup Custom Object: –

Go to Setup -> Create -> Objects -> New -> Name it “LinkedIn Information

LinkedIn Informations

Create a VF page and Controller Class: –

Create an Apex class Name it “LinkedlnoAuthController

Go to Setup -> Develop -> Apex Classes -> New -> 

Next, Create a VF page that will do the Authorization with LinkedIn. Name it “LinkedlnoAuth“.

You will get the complete code from my GitHub Repo. Copy Apex Class and VF page code From Here.

After you created VF page Preview it, Copy the URL and paste somewhere into the notepad++ or any other text editor. URL will be something like below

https://dreamhouse-a-dev-ed–c.ap5.visual.force.com/apex/LinkedlnoAuth

Create an App in LinkedIn: –

Time to create a Connected App into LinkedIn developer account to get the Client Id (Consumer Key)  and Client Secret(Consumer Secret).

Go to LinkedIn Developer Console Create Application. Refer this link to get the complete picture of app configuration. You will get Client Id and Client Secret copy both and store in the text editor.

You LinkedIn app page will look like below

LinkedIn - Application

Make Required Changes into Apex Class: –

1 – Open LinkedlnoAuthController class replace redirect_URI with your VF page preview URI (line #10).

2 – Replace consumerKey with your client Id and consumerSecret with your Client Secret (line #8 and #9).

Now, we are all set to let’s do some testing and see if we have successfully integrated LinkedIn with Salesforce.

Open LinkedlnoAuth VF page and preview it. Click Connect with LinkedIn button, it will open a new screen asking your LinkedIn username and password

Connect with Linkedln

Linked Login

Enter your username and password then sign in Grant permission to Application -> Click Complete Authorization, a success message will show.

Linked Login.png

Now Click on Get Basic Info -> A basic information will show here in PAGE

Basic Info.png

Facing any issue let me know in the comment section.

Happy Coding 🙂 Enjoy Coding 🙂

Salesforce – Google Calendar Integration tips and tricks

Hello friends, In this post, I will show you how you can integrate Salesforce with Google Calendar so that Salesforce user could aware of all upcoming events and tasks!

Below is the list of all the tasks that we will do in this post to do Integrate Google Calendar with Salesforce.

  1. Create a public List type Custom SettingGoogleCalenderInfo” to store the access/refresh token and expiry time (in Seconds).
  2. Enable Google Calendar API and create an App to get the Consumer Key and Consumer Secret
  3. Create VF page Apex Class to make the callout and store Access/Refresh Token into Custom Setting.
  4. Create Another VF page which will fetch all the List of Calendar Available into your Calendar and create a new Calendar From Salesforce.

Create New Custom Setting: –

Login into Your Salesforce Org and go to Setup -> Develop -> Custom Settings -> New

See below image for the field names and data types

Custom Setting

Create Required VF pages and Apex Classes: –

  • Open Developer Console and Create 2 Apex Classes GoogleCalenderApi and GoogleCalendarActionsController.
  • Now, Create 2 VF pages “GoogleCalendarActions” and “GoogleCalenderoAuth”
  • You will get the Complete code for All the pages and Apec Classes From Here copy the code and paste in your pages/classes.

Do Enable Google Calendar API and Settings: –

Go to  Using OAuth 2.0 to Access Google APIs and you will get Detailed Information about authentication process.

Go to Google API Console, Credentials -> Create Credentials -> oAuth Client Id

1

Application Type -> WEB

Authorized redirect URIs -> URL To Your VF page “You already have created the VF page if not follow the above steps and create both the pages with classes”

Open “GoogleCalenderoAuth” VF page, Click Preview and Copy the URL that URL is the Redirect URI paste that URL here.

Note: – You also need to replace “redirect_uri” variable in GoogleCalendarAPI class with your VF page URL. 

VF PAGE Preview.png

Now, Click Create, a Pop up with Client Id and Client Secret will open

2

3

Copy both Client Id and Client Secret in any text Editor like notepad++, notepad, or any editor.

Now, Open GoogleCalenderApi class replace consumerKey with your Client Id and clientSecret with your Client Secret.

Now, as we have done all the necessary steps and it’s show time.

Open “GoogleCalenderoAuth” VF page, preview it Page will look like below

VF page.png

Click “Connect With Calendar” you will be redirected to Gmail Login, Login with your Gmail, Grant Access to Application. You will get back to the same Page and Now Click “Get Access Token” a new Page “GoogleCalendarActions” will open.

VF page.png

VF page

First, we will create a New Calendar, Enter “Testing Google API ” and then Create New Calendar. You will get a Success Message with the response.

Create New Calendar

Now, List All Calendars will list all the calendars that are available to your Account.

List All Calendars.png

Note: – Using the Above Code of “GoogleCalenderoAuth” Page and “GoogleCalenderApi” Apex Class you can integrate with Any Google API. You only need to make a minor change which is the value of the calendar_Scope variable in GoogleCalenderApi class, use the scope of the API that you want to Connect. You will get the scope of all the APIs OAuth 2.0 Scopes for Google APIs.

Any Queries come in the comment section.

 

When Salesforce Admin should Code

When Salesforce Admin Should Code

Hi Friends, Hope you all are enjoying my posts. In this post, I will let you all especially Salesforce Admins when they should code, in other words, what are the scenarios when admin need to code.

I came up with some scenarios where admin should go for the code.

1 – Throw an Error message When trying to delete Account that has Closed Won Opportunity.

We can not show the Error message when trying to delete the account which has Closed Won Opportunity using any Salesforce  Out-of-Box functionality. So, admin should go for Apex Trigger to show the proper Error message.

1.png

2.png

Use below code for trigger to show the error


trigger AccountTrigger on Account (before delete) {
// Prevent the deletion of accounts if they have related won opportunities.
if(Trigger.isBefore && Trigger.isDelete){
for(Account acc : [Select Id, Name, (Select Id, Name From Opportunities WHere IsClosed=true) From Account
WHere Id IN : Trigger.oldMap.keySet()]){
if(acc.Opportunities.size() > 0){
trigger.oldMap.get(acc.Id).addError('Can not Delete Account, Because Account have one or more Closed Opportunity ');
}
}
}
}


4.png2 – Restoring the duplicate Data from the Recycle bin. A Salesforce admin should go for apex trigger in order to prevent the duplicate record in Salesforce Database

3 – Update Associated Contacts when a User is created or Update.

Another example where admin should code is the requirement to update the associated contact whenever a user is created or updated.

UserTrigger


trigger UserTrigger on User (After insert, After Update) {
/* Take a set of Id to store the Contact Ids */
Set contactIdsSet = new Set();
/* prepare a Map with Contact Ids and User Name */
Map contactIdswithUserName_Map = new Map();
for(User u : Trigger.New){
if(u.ContactId != null){
contactIdswithUserName_Map.put(u.ContactId, U.Name);
}

}

/* Call handler Class method to update Contact with Respective User FirstName + LastName */
UserTriggerHandler.updateContacts(contactIdswithUserName_Map);
}

 

UserTriggerHandler – Use @future annonation to make the dml


public class UserTriggerHandler{

@future
public static void updateContacts(Map contactIdswithUserName_Map){
List contactList = new List();
contactList = [Select Id, Name, UserName__c From Contact Where Id IN : contactIdswithUserName_Map.keySet()];
for(Contact c : contactList){
c.UserName__c = contactIdswithUserName_Map.get(c.Id);
}

update contactList;
}
}

4 – Writing the Rollups for the lookup Relationship

Rollup the child record data into parent record.

See the post here

5 – Automatic Lead Conversion

Convert Lead automatically when lead reaches the certain stage. like Qualified, or any other stage that you want.

To do this you can go for process builder which will call an apex class method and do the conversion

OR

Create a trigger on Lead object and then call the handler class method

trigger code


trigger LeadTrigger on Lead (After Insert, After Update) {
List leadIdsSet = new List();
for(Lead l : Trigger.New){
if(l.status == 'Qualified')
leadIdsSet.add(l.id);
}

LeadTriggerHandler.convertLeads(leadIdsSet);
}

Handler Class Code


Public class LeadTriggerHandler
{
public static void convertLeads(List LeadIds)
{
/* fetch the converted Status */
LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
List LeadconvertList = new List();
for(id currentlead: LeadIds){
Database.LeadConvert Leadconvert = new Database.LeadConvert();
Leadconvert.setLeadId(currentlead);
Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion
LeadconvertList.add(Leadconvert);
}

if (!LeadconvertList.isEmpty()) {
List lcr = Database.convertLead(LeadconvertList);
}
}
}

Whenever I will found more scenarios then I will update this post!

Any questions comment below enjoy learning enjoy salesforce.

Sharing is caring 🙂

 

 

Difference between Render, reRender and renderAs

Most of the Salesforce Developers are confused when to use render, reRender, and reRender. So, here is explanation

Render: – Is used to show/hide the particular block, output panel or input/output fields based on the condition.

Example: – You have 2 fields one is visible and second is hidden, you want the second field to be visible when the first field is filled then use render.

<apex:pageBlockTable value=”{!empList}” var=”emp” rendered=”{!empList.size > 0}”>
                  <apex:column value=”{!emp.Name}”/>
</apex:pageBlockTable>

reRerender: – Is used to refresh the particular output panel, block, and or fields after a server request has been completed. It uses Id to reRender.

Example: – You have a VF page where you want to add Contacts related to Account and also wanted to show the recently added Contacts then use reRender to refresh the block which is showing the contact list.

renderAs: – Is used to open the Visualforce Page in different format like- HTML, pdf, and excel

Example: – To show the invoice in PDF format.

for pdf – renderAs =”pdf”

for HTML – renderAs =”html”

for excel – <apex:page controller=”contactquery” contentType=”application/vnd.ms-excel#SalesForceExport.xls” cache=”true”>

For more info Visit Export data in Excel or PDF format using Visualforce

Difference between Action function, Action Support, and Action Poller

Action Function: –

Action Function is used in the Visualforce page to call the Service Side method using JavaScript and does not add the Ajax Request before calling the Controller method.

<apex:actionFunction name=”myactionfun” action=”{!actionFunctionTest}” reRender=”pgBlock, pbSection” />

Let us talk about above example. In any Javascript Method where the name of ActionFunction ( In our example myactionfun() ) will be invoked, it will call the controller method name actionFunctionTest. Example myactionfun();

Action Support: –

As the name indicates action support is used to provide the support to the input field where we can not get event either manually or external event. It adds the AJAX request to VF page and then Calls the Controller method. For

For example, if we want to call any server side method when input changes then we will go for action support because we can not get any event for this.

<apex:inputText value=”{!dummyString}” >
                      <apex:actionSupport event=”onchange” action=”{!actionSupportTest}”                                     reRender=”pgBlock, pbSection” />
</apex:inputText>

Action Poller: –

A timer that sends an AJAX request to the server according to a time interval that you specify. Each request can result in a full or partial page update.

<apex:actionPoller action=”{!incrementCounter}” reRender=”counter” interval=”15″ enabled = “true” />

Enabled attribute is used to make poller as active or inactive by default value is true. If we provide false then poller will be inactivate.

Untitled

Click Here for Live Demo.

For Complete Code Click Here.

Any questions come up in comment Section!