count
will always be 1 because when the class is called, you're declaring a new Integer as 0, adding 1 and creating a new record with the value 1.
From what I can see, there's one of two scenarios you want:
- Create a new record when a visit is recorded
- Get a User's Tracking_1__c record for a particular page and increment their count.
First Scenario
In the first instance, you could literally, each time a User visits a page, create a record:
public class EditCustomerData {
public void trackVisits() {
Tracking_1__c track = new Tracking_1__c(
Users__c = UserInfo.getUserId(),
Datetime_Visited__c = datetime.now(),
VF_Page_Visited__c = 'apex/EditCustomerData',
);
INSERT track;
}
}
Then you can write a simply query to see how often a page is visited:
Integer count = [SELECT Count() FROM Tracking_1__c WHERE User = :myUser AND VF_Page_Visited__c = '/apex/EditCustomerData'];
There's an argument to say you don't need the Datetime_Visited__c
because the CreatedDate would be just that.
Second Scenario
You would need to do a few things:
- Check if a User has a record for a page
- If they don't, create it, otherwise get it
- Get the
Count__c
value
- Add 1
- Update it
It might look like below:
public class EditCustomerData {
public void trackVisits() {
// Get a list of tracking records
Tracking_1__c[] trackingRecord = [SELECT Counter__c FROM Tracking_1__c WHERE Users__c = :UserInfo.getUserId() AND VF_Page_Visited__c = '/apex/EditCustomerData' LIMIT 1];
if (trackingRecord.size() > 0) { // Did the query return a record?
Integer counter = trackingRecord[0].Counter__c; // Assign counter to an Integer
counter = counter + 1; // Add 1
trackingRecord[0].Counter__c = counter; // Set counter to the new count
}
else { // If there's no record...
trackingRecord.add(new Tracking_1__c( // ... Create a new one
Users__c = UserInfo.getUserId(),
Datetime_Visited__c = datetime.now(),
VF_Page_Visited__c = '/apex/EditCustomerData',
Counter__c = 1;
));
}
UPSERT trackingRecord; // UPSERT (Update or Insert a record)
}
}
The only problem I could see here is that Datetime_Visited__c becomes redundant. It will just show the last time a User visited the page.
As I mentioned in the comments, you might be better waiting for Summer '17 as they're doing something that will track views to a Page. Although, from what I've experimented with doesn't show it by User, only the total.