I have developed one visualforce page and controller for account object and checking account.type is empty or not. If account.type is empty then page should be redirect to other page, this should be execute whenever page is reload or refresh. I called docheck method inside constructor but page is not redirecting to other page when account.type is empty.

Can anybody help me on this requirement

public class myaccountcontroller
  public String accId {get;set;}

  public myaccountcontroller(ApexPages.StandardController sc)
    accId = ApexPages.CurrentPage().getparameters().get('id');

  public PageReference doCheck()
     Account acc = [SELECT Id,Name,Type FROM Account WHERE Id=:accId];

     if(acc.Type =='')
        PageReference mainHome= Page.Custom_Error_Page; 
        return mainHome;

<apex:page standardcontroller="Account" extensions="myaccountcontroller">
  • 2
    This design, no matter how you approach it, will not work for the purpose you've intended. Instead, you're probably going to want to disable the save button and simply show an ApexPages.Message so they can read the error.
    – sfdcfox
    Commented Dec 12, 2018 at 17:35
  • BTW if (String.isBlank(acc.Type)) ... is the preferred construction as it tests for both null and empty string
    – cropredy
    Commented Dec 12, 2018 at 18:22

1 Answer 1


While doCheck() is returning a redirect, it's doing so in the constructor. Since the constructor does not and cannot return a PageReference, the redirect is never actually reaching the page. You'll need to update your Visualforce page so that it it calls doCheck() through an action, which will then return the redirect to the page. Please see the following documentation on actions.


On a side note, there's a good chance you're getting an SObject exception for accessing an un-queried field. You're checking if acc.Type == '', but you didn't include Type in your field list in you account query.

  • I have added Type field on soql query but i missed that add here. If i call docheck() method with action attribute on apex:page tag then it is always redirecting to second instead of execution of first page. Commented Dec 13, 2018 at 6:20
  • I'm not sure why you would want it to only redirect on refresh. Instead of instantly redirecting, you could have a warning pop up where the redirect action is on the confirm button. Commented Dec 13, 2018 at 15:11
  • If you really want to redirect on reload, you can create an actionFunction for doCheck that runs on page unload. <element onunload="doCheckActionFunction">. Note that it will redirect if you leave the page at all. So if you want to limit it to just refreshes, you'll need to compare the URLs and only redirect if the new URL matches the current URL. Commented Dec 13, 2018 at 15:14

You must log in to answer this question.

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