Creating ADF Faces Comamnd Button at Runtime

Posted by Frank Nimphius on Oracle Blogs See other posts from Oracle Blogs or by Frank Nimphius
Published on Tue, 22 Nov 2011 02:17:58 -0600 Indexed on 2011/11/22 10:12 UTC
Read the original article Hit count: 294

Filed under:

In ADF Faces, the command button is an instance of RichCommandButton and can be created at runtime. While creating the button is not difficult at all, adding behavior to it requires knowing about how to dynamically create and add an action listener reference. The example code below shows two methods: The first method, handleButtonPress is a public method exposed on a managed bean.

public void handleButtonPress(ActionEvent event){ 
 System.out.println("Event handled"); 
 //optional: partially refresh changed components if command 
 //issued as a partial submit
}

The second method is called in response to a user interaction or on page load and dynamically creates and adds a command button. When the button is pressed, the managed bean method – the action handler – defined above is called. The action handler is referenced using EL in the created MethodExpression instance. If the managed bean is in viewScope, backingBeanScope or pageFlowsScope, then you need to add these scopes as a prefix to the EL (as you would when configuring the managed bean reference at design time)

//Create command button and add it as a child to the parent component that is passed as an 
//argument to this method
private void reateCommandButton(UIComponent parent){
  RichCommandButton edit = new RichCommandButton();
  //make the request partial
  edit.setPartialSubmit(true);
  edit.setText("Edit");                         
  
  //compose the method expression to invoke the event handler
  FacesContext fctx = FacesContext.getCurrentInstance();
  Application application = fctx.getApplication();
  ExpressionFactory elFactory = application.getExpressionFactory();
  ELContext elContext = facesCtx.getELContext();
  MethodExpression methodExpressio = null;
  //Make sure the EL expression references a valid managed bean method. Ensure
  //the bean scope is properly addressed 

  methodExpression =  elFactory.createMethodExpression( 
                            elContext,"#{myRequestScopeBean.handleButtonPress}", 
                            Object.class,new Class[] {ActionEvent.class});
  //Create the command buttonaction listener reference

  MethodExpressionActionListener al = null;        
  al= new MethodExpressionActionListener(methodExpression); 
  edit.addActionListener(al); 

   //add new command button to parent component and PPR the component for 
   //the button to show
   parent.getChildren().add(edit);
   AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance(); 
   adfFacesContext.addPartialTarget(parent); 
}

© Oracle Blogs or respective owner

Related posts about /Oracle/ADFv