Binding Component Instance to a Bean Property

JavaBeans are used to associate the UI components.

Binding Component Instance to a Bean Property

Binding Component Instance to a Bean Property

        

JavaBeans are used to associate the UI components. This backing bean (JavaBean) contains properties that are bound to either component value or component instance. Both types of binding requires use of Expression Language (EL) syntax. A component instance can be bound to the bean property by referencing the property in the "binding" attribute of the tag associated with the component. But we have to take care of one fact that the property of the bean must accept and return the same component type as the instance of the bound component.

For example:

<h:panelGrid columns="2" binding="#{InstanceBean.gridInstance}">
<h:outputText value="First Name: "/>
<h:outputText value="Ravi"/>
<h:outputText value="Last Name: "/>
<h:outputText value="Kant"/>

<h:outputText value=""/>
<h:commandButton value="#{InstanceBean.buttonBorderText}" action="#{InstanceBean.setBorder}"/> 
</h:panelGrid>

The related property in the backing bean should be of the class type of component and its setter and getter method should deal with same type. For example, In the code below, gridInstance attribute is of type HtmlPanelGrid class which represents the panel grid component. Now you can use this object in action method and manipulate the panel grid as you want.

The sample code for InstanceBean.java:

package roseindia;

import javax.faces.component.html.HtmlPanelGrid;

public class InstanceBean {

HtmlPanelGrid gridInstance;
........................................
........................................
public HtmlPanelGrid getGridInstance() {
  return gridInstance;
}
public void setGridInstance(HtmlPanelGrid gridInstance) {
  this.gridInstance = gridInstance;
}

......................................
......................................
public void setBorder(){

  if(buttonBorderText.equals("Set Border")){
   gridInstance.setBorder(1);
   gridInstance.setBgcolor("pink");
   buttonBorderText = "Remove Border";
  }
  else{
   gridInstance.setBorder(0);
   gridInstance.setBgcolor("white");
   buttonBorderText = "Set Border";
  }
  }
..................................
...................................
}

 

Download code for all examples