Monday, January 27, 2014

Cancelling ADF Action from ActionListener

Sometimes we are faced with a requirement that requires the use of both action and action listener attributes of the command components of ADF.
 It seems that a lot of people advice to use the ActionListener to do some validation on the page level, then if it's okay let the code proceed with the code representing the business requirements in the Action.

but how are we supposed to stop the processing of the current event, so that the action is not invoked?
I will list three different code sample to achieve this.
1)using the setAction of the component:
if (some validation logic here) {
message("Valid");
Class[] parms = new Class[] { };
MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding("#{ClassName.MethodName}", parms);
((RichCommandButton)actionEvent.getSource()).setAction(mb);
} else {
message("Invalid");
((RichCommandButton)actionEvent.getSource()).setAction(null);
}

Note: MethodBinding is a deprecated class, use the code in example 2.
2)using the setActionExpression of the component:
if (some validation logic here) {
message("Valid");
Class[] parms = new Class[] { ActionEvent.class };
FacesContext fctx1 = FacesContext.getCurrentInstance();
ELContext elctx = fctx1.getELContext();
Application app = fctx1.getApplication();
ExpressionFactory exprFactory = app.getExpressionFactory();
javax.el.MethodExpression expr = exprFactory.createMethodExpression(elctx, "#{ClassName.MethodName}", parms);
((RichCommandButton)actionEvent.getSource()).setActionExpression(expr);
} else {
message("Invalid");
((RichCommandButton)actionEvent.getSource()).setActionExpression(null);
}
3)or simply use the javax.faces.event.AbortProcessingException
if (some validation logic here) {
message("Valid");
} else {
message("Invalid");
throw new AbortProcessingException("Invalid");
} 
from the java doc:
public class AbortProcessingException
extends FacesException 
An exception that may be thrown by event listeners to terminate the processing of the current event.

No comments:

Post a Comment