2

How to get the count of number of times a Visualforce Page is opened using APEX only(if possible)?

3 Answers 3

2

You must be using some controller with the visualforce page, so I would suggest:

  1. You should create a custom setting with a number field with 18 length.

  2. you can write an action method in your controller and use that in action attribute of the page, this method will be executed as soon as your page will be loaded.

You can not use constructor here because constructor doesn't allow DMLs.

<apex:page controller="yourController" action="{!updateCustomSetting}">

Your controller would be like:

public class yourController{
  public void updateCustomSetting(){
    //update your custom setting here with increment.
  }
}
0
  1. Call the apex method from controller.
    • this should be called from action attribute in apex:page
  2. Increment the counter
    • create a custom setting and store the counter value there. This value should be incremented when you load the vf page.
0

I would do this by creating a custom object, and creating a new record whenever your page is visited. This has a few advantages over incrementing a single record:

  1. It avoids the concurrency problem (two people access the page at the same time, both get back the same number of accesses (say 5), both update with the same increment (6), and now it says 6 when it should say 7). This can be overcome by specifying FOR UPDATE in the SOQL call to retrieve the object, but that introduces other issues
  2. It keeps track of when the page was accessed and who accessed it, so you can report on traffic patterns with more granularity
  3. It opens the door for more tracking later on, such as the user's browser, what links they clicked on, etc

As noted in the other answers, this record would have to be created in an action method in the controller, as DML is not permitted while the Page Constructor is running.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .