3/05/2011

How to trigger an ICEfaces / JSF action by javascript

How do you call an ICEfaces backing bean action by using javascript ? Even in Liferay ?


Well, in the same way as you would do it, if you were a human: Find the button that correspondes to the action and click it.


Find the button to click


You can get the button by finding out its unique id. This is something you do in your backing bean and provide by using an ice:outputText:


Your Bean


Your backing bean provides an HtmlCommandButton property that you will bind to in your view. It also returns the clientId of your button (this is the unique ID of your button). This works in pure JSF / ICEfaces environments as well as in a Liferay server.


package de.test;
import javax.faces.bean.ManagedBean;
import com.icesoft.faces.component.ext.HtmlCommandButton;


@ManagedBean
public class IdBean {


HtmlCommandButton button = new HtmlCommandButton();

public HtmlCommandButton getButton() {
return button;
}
/**
* Returns the client id of the command button.
*  
* @return
*/
public String getId(){
return button.getClientId();
}

/**
* The action to call
*/
public void myaction(){
// do stuff ...
}
}

Your View

In your view you will first bind your button to the HtmlCommandButton property in your bean. Then yuo will retrieve the id of your button by using an ice:outputText. Then you can get the button by using standard javascript calls.

[...]

<script language="JavaScript1.1"> 

function buttontest(){
   var buttonId = '<ice:outputText value="#{mailDistributionListManagementTab.inputControlId}" nospan="true"/>';
   var button = document.getElementById(buttonId);
   button.click();
}
</script>



[...]


<ice:commandButton visible="hidden" binding="#{idBean.button}" action="#{idBean.myaction}"/>


If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)


If you have any questions, feel free to leave a comment.