I want to add a tab to my app that loads a record based on the currently logged in user. Is there a way to do that easily or am I going to have to develop the VF page using a custom controller and handcraft the entire thing? I have created and dummy VF page and used the URL to append a ?id= manually to test it but I want to have the page load the ur and populate the ID based on the current user.

The record I want to load is a custom object which has a lookup field to the user object so there is a field on the custom object that I can reference. Being relatively new to the VF world I'm not sure if there is a way to run code "before" the page is rendered except using a custom controller.


This pattern should work.

You write a page that does nothing more than call a controller method (via the action attribute) and that method can return a different page that is displayed instead of his first page:

<apex:page controller="YourObjectController" action="{!redirect}">
    No record found for you.

Then the controller just contains the logic to identify the right page:

public with sharing class YourObjectController {
    public PageReference redirect() {
        YourObject__c[] sobs = [
                select Id
                from YourObject__c
                where User__c = :UserInfo.getUserId()
                order by CreatedDate desc
                limit 1
        if (sobs.size() == 1) {
            // Go to the default layout page for the right object ID
            return new PageReference('/' + sobs[0].Id);
        } else {
            // Stay on same page that has a hard-coded error message
            return null;

The user doesn't see the first page at all.

The apex:page documentation explains the action attribute like this:

The action method invoked when this page is requested by the server. Use expression language to reference an action method. For example, action="{!doAction}" references the doAction() method in the controller. If an action is not specified, the page loads as usual. If the action method returns null, the page simply refreshes. This method will be called before the page is rendered and allows you to optionally redirect the user to another page. This action should not be used for initialization.

  • Excellent, I'll give it a try and let you know, thanks Keith. – chriscwharris May 9 '16 at 10:30
  • Finally tried this eons later and got it working! Thanks Keith! – chriscwharris Oct 19 '16 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.