6

I want to redirect from a visualforce page to a custom obect's list page. I need to run a method in the controller as th action for the button, so I would like to redirect from the controller.

I found this doc on how this doc on how to redirect to a standard object list page, but I need to redirect to a 'Custom Object's List Page', and I need to do it from a controller, not the VF page itself.

Is this possible?

12

You could get the object prefix, which returns the first 3 characters in the object's ID. Then construct an URL and redirect to it.

Create this method:

public static PageReference listView(Schema.sObjectType destinationSObject) {
   Schema.DescribeSObjectResult destination = destinationSObject.getDescribe();
   PageReference pageRef = new PageReference('/' + destination.getKeyPrefix() );
   pageRef.setRedirect(true);
   return pageRef;
    }

Call this method:

// Redirect to the Account List View
return listView(Account.sObjectType); 

// Redirect to Some Custom Object's List View
return listView(Some_Custom_Object__c.sObjectType);

If you need to get to the landing page append a /o after the result.getKeyPrefix():

PageReference pageRef = new PageReference('/' + result.getKeyPrefix() + '/o');
  • 2
    result.getKeyPrefix() is actually a tighter solution than my String/Substring snippet... Great answer. (If only I hadn't spent all that time on screenshots!) – Simon Lawrence Jan 24 '14 at 10:33
3

You can link to the "tab" style page (I figure this is the list page you are asking about) by redirecting to the first three characters of the record ID... as this represents the object type.

As you can see here the ID of my custom test object....

object page

The first three characters is the list page URL

list page

So if you had a page, with a custom controller, with an object in it, stick a button on the VF page that calls your action

<apex:commandButton value="GO!" action="{!buttonGo}" />

And then in your controller, you can do something like this to send the user off to the relevant URL

public with sharing class testExtensions {

    public Test_Object__c tester { get; set; }

    public testExtensions(ApexPages.StandardController controller) {
        this.tester = (Test_Object__c)controller.getRecord();
    }

    public PageReference buttonGo()
    {
        PageReference pr = new PageReference('/' + String.valueOf(tester.Id).substring(0,3));
        pr.setRedirect(true);
        return pr;
    }

}

... You haven't said what is in your controller/what it does, so I can't speculate any better than that?? Hopefully this is enough to get your over the line though!

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.