[SalesForce] Displaying an error on the page (from the controller)

I was trying to redirect to an error page from the Controller, but somehow that doesn't work. The code works, but the unit tests don't support that piece of code.

Check this discussion

What would be different ways to display an error on the page right from the constructor.

One that I could think of is to have a

<apex:pagemessage summary="error message..." rendered="{!variable}">

And set this variable in the page constructor, so when it loads with some bad data; it will show up this error.

What are the other ways to do this?

Best Answer

There are several different ways you could do this. The example you gave is one option. I'm not sure the constructor is the best place to be testing data, but...it could work.

You could also (depending on the circumstance) check the data in your getters. You could do some interesting things with this. For instance, if the page you're building allows the user to edit a record's fields, but you've found that there's bad data in one of the fields, you could display an error message specific to that field, and leave the field blank...possibly forcing the user to enter a valid value before saving the record.

<apex:inputText value="{someValueX}"/>
<apex:outputText value="Please enter a proper value for X in the field above" rendered="{!isErrorOnValueX}">

.

public Boolean isErrorOnValueX = false;
public Boolean isErrorOnValueY = false;

public String getSomeValueX(){
    if(...){
        // if this is bad data, ...
        isErrorOnValueX = true;
        return null;
    } 
    return someValueX;
}

I know from our previous discussion that you ideally wanted to redirect to a new page when some data didn't meet your requirements. You were trying to return a pageReference, or find some other way of redirecting the user to another page from inside the constructor.

If you're preference is still to redirect the user to a new page, you could combine the idea you're describing here -- setting a variable based on whether or not you've found bad data -- and using that variable in a pageReference method that you would call on page load. (I.E., from the apex:page tag's "action" property.)

<apex:page controller="myController" action="{!badDataTest}">

.

public class myController {

    public Boolean isBadData {get; set;}

    public myController {
        // ...constructor logic here...
        // Also test for bad data. Set isBadData = true if the data is no good; otherwise set to false.
    }

    public pageReference badDataTest(){
        if(isBadData){
            pageReference p = Page.myErrorPage;
            p.setRedirect(true);
            return p;
        }
        return null;
    }

}
Related Topic