Hi,
today I will show you a nice solution to clear or refresh input fields. This solution does this with the Direct-2-Dom abilities of ICEfaces. I would not like to use the Render API of ICEfaces because there are some drawback I would not like to handle with. So this solution does not use any special Rendering API of ICEfaces and is very easy to integrate it into existing code without to much refactoring.
So lets beginn, here is the source code:
public static void cleanBackingBean(String beanName)
{
try
{
ValueExpression binding = context.getApplication().getExpressionFactory().createValueExpression(elContext, "#{" + beanName + "}", Object.class);
Object object = binding.getValue(elContext);
object = Class.forName(object.getClass().getName()).newInstance();
setBackingBean(object, beanName);
clearSubmittedValues(beanName);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void clearSubmittedValues(String beanName)
{
FacesContext context = FacesContext.getCurrentInstance();
UIViewRoot viewRoot = context.getViewRoot();
List<UIComponent> uiComponentList = viewRoot.getChildren();
for (UIComponent uiComponent : uiComponentList)
{
clearSubmittedValues(uiComponent, beanName, context);
}
}
private static void clearSubmittedValues(UIComponent component, String beanName, FacesContext context)
{
if (component instanceof UIInput)
{
try
{
if (component.getValueExpression("value").getExpressionString().indexOf(beanName) > -1)
{
PassThruAttributeRenderer.renderAttributes(context, component, new String[0]);
}
}
catch (NullPointerException ingnore)
{
// Nothing to log here. The NullPointerException just means that there is no ValueExpression found with name 'value'.
}
}
List<UIComponent> childenList = component.getChildren();
if (childenList.size() > 0)
{
Iterator<UIComponent> childIter = childenList.iterator();
while (childIter.hasNext())
{
clearSubmittedValues((UIComponent)childIter.next(), beanName, context);
}
}
}
The “cleanBackingBean” method just takes the beanName (as defined in the faces xml). And creates a new instance (which means empty) of this bean and set it back to the application context.
The “clearSubmittedValues” method search for all input fields in the view that are associated with the given bean and set them to rerender in the response phase.
Thats all the magic. The “clearSubmittedValues” method can be optimised. The search for the solution took me some time, so I hope it will help others to move on faster.