VMOrtega
VMOrtega

Reputation: 1978

apex:commandButton can't return nothing?

I have:

<apex:commandButton action="{!whatever}" value="myButton" reRender="sectionX" />

And

public String whatever(){
    return 'ok';
}

It doesn't work (returns 401 Unauthorized), but if I write:

public void whatever(){
    // some code
}

works fine.

The question is: how can I return something (a JSON or a Page) to this call?

Thanks

Upvotes: 0

Views: 3306

Answers (2)

Gerard Sexton
Gerard Sexton

Reputation: 3210

CommandButtons are used to execute some code on the server and they return a PageReference, not a string/json value.

<apex:commandButton action="{!whatever}" value="myButton" reRender="sectionX" />

So the method whatever should do the work and then assign the result to a public property on the controller so the page can display the result. The rerender attribute says to reload the data in the outputpanel sectionX. SectionX needs to enclose the results you want to display from the commandbutton action.

public class myController {
    public string Result {get;set;}

    public PageReference whatever() {
        // do your work here
        Result = DateTime.Now();
        return null;
    }
}

Visualforce

<apex:outputpanel id="sectionX">{!Result}</apex:outputpanel>

Every time you click myButton command button the outputpanel will display a new datetime string.

An afterthought: If you want to put a string result/JSON into a javascript method, you can do something like the following.

<script>    
    function processJSON(val) {
    var res = JSON.parse(val);
    // do your work here
    }
</script>

<apex:outputpanel id="sectionX">
<script>
 processJSON("{!Result}");
</script>
</apex:outputpanel>

In your example commandbutton code you used rerender so you dont need to return a non null PageReference. If, on the other hand, you want to go to another page when you click the commandbutton, you would not set the rerender attribute and you would need to return a non-null PageReference, ie

public PageReference whatever() {
    return Page.MyVisualforcePage;
}

Upvotes: 2

Andrii Muzychuk
Andrii Muzychuk

Reputation: 1188

Not realy. Look here As for me, I used method which returns PageReference variable.

Better to do like this:

public PageReference whatever(){
    PageReference pageRef = null; // null won't refresh page at all if I'm not mistaken
    // some cool logic goes here
    if(toNavigate) {
      pageRef = new PageReference('here is some URL to which user must be navigated');
    } else if(toRefreshCurrent) {
      pageRef = ApexPages.currentPage();
    }

    return pageRef;
}

About returning page - look here.

Upvotes: 1

Related Questions