Tuesday, June 21, 2011

Button Action Not Firing in JSF

We see this one a LOT.

The action listener in JSF isn't complicated at all and yet it seems like half the time something as simple as clicking a commandButton can cause problems.

Today's Example:

Liferay 6.0.6
Tomcat 6
Windows 7
ICEfaces 1.8.1
Sun JSF 1.2

Some code from the view.xhtml page:

<ice:selectManyMenu style="width:150px;" value="#portletBacking.currentsite}">
<f:selectItems id="siteList" value="#{sites.sites}" />
</ice:selectManyMenu>
<ice:commandButton actionListener="#{portletBacking.add}"
name="addButton" type="submit" value="Add"/>

And the add() method from the backing bean:

public void add(ActionEvent e){
System.out.println("Adding...");
//A bunch of processing...
}

Clicking the button did NOTHING. It didn't even print the "Adding..." message to standard output. Why? Was the action method set up properly? Yes. Was the backing bean registered in faces-config.xml? Yes.

What happens sometimes is that JSF gets stalled when there's an incorrect return type on a control. One way to figure out which control is causing the problem is to comment out the page controls and add them back in, one at a time, until the problem happens again. That's what I did, and in this case the flaw was in the ice:selectManyMenu control. Here's the code that was linked to the value:

public void setCurrentsite(String currentsite) {
this.currentsite = currentsite;
}

public String getCurrentsite() {
return currentsite;
}

See the problem?

The ice:selectManyMenu doesn't take a String value. It takes a String[]. If I had been working with an ice:selectOneMenu this would have been correct. All I had to do was fix the code to use a String[] instead:

public void setCurrentsite(String[] currentsite) {
this.currentsite = currentsite;
}

public String[] getCurrentsite() {
return currentsite;
}

And voila'! The action fired when I clicked the button.

So if you're having this problem and everything else seems right, start taking a closer look at the other controls on the page.

If that doesn't fix it, take a look at this.

No comments:

Post a Comment