miercuri, 4 noiembrie 2015

Custom VisitCallback implementation for resetting editable values of a form

Write a custom VisitCallback implementation for resetting editable values of a form:

public class CustomVisitCallback implements VisitCallback{
 @Override
 public VisitResult visit(VisitContext context, UIComponent target) {

  if (!target.isRendered()) {
      return VisitResult.REJECT;
  }
  if (target instanceof EditableValueHolder) {
     ((EditableValueHolder)target).resetValue();
  }

  return VisitResult.ACCEPT;
 }
}

Let's start the process of visiting nodes using the following code:

FacesContext context = FacesContext.getCurrentInstance();
UIComponent component = context.getViewRoot();
CustomVisitCallback customVisitCallback = new CustomVisitCallback();
component.visitTree(VisitContext.createVisitContext(context), customVisitCallback);

Note that the starting point in the traversal process is the view root. This is not mandatory; you can pass any other sub-tree. Per example, you may want to reset the inputs only of the current submitted form. This can be easily accomplish via OmniFaces, Components#getCurrentForm().

import org.omnifaces.util.Components;
...
FacesContext context = FacesContext.getCurrentInstance();
UIForm currentForm = Components.getCurrentForm();
CustomVisitCallback customVisitCallback = new CustomVisitCallback();
currentForm.visitTree(VisitContext.createVisitContext(context), customVisitCallback);

Niciun comentariu:

Trimiteți un comentariu