Tuesday, February 1, 2011

Auto Focus in ADF : Revisit

Auto focus on the first or name field of a jsff is difficult if it is loaded dynamically.

Here is one solution:

1) In your page or template add the following non visible text fields near the end of your page(these will set the client id of your field and execute some javascript):

<af:inputText clientComponent="true" id="hit7" value="#{formBean.focusId}" visible="false"/>

<inputText clientComponent="true" id="hit8" value="#{formBean.focusScript}" visible="false"/>

2) Backing bean (MUST use view scope):
//member variables
 private boolean mustExecuteAutoFocus = false;
 private String clientFocusId = null;
 //Constructor - this will be called when the taskflow id changes in the region
 public FormBean(){
  mustExecuteAutoFocus = true;
 }
 public String getFocusId(){
  //here you can use a bound component or find a component in the view root by id etc to get your id or just hard code it
  UIComponent comp = findFirstInputTextComponent();
  if (comp == null){
   setClientFocusId(null);
   return null;
  }
  setClientFocusId(comp.getClientId(FacesContext.getCurrentInstance()));
  return getClientFocusId();
}

public String getClientFocusId(){
 return clientFocusId;
}

public void setClientFocusId(String clientFocusId){
 this.clientFocusId = clientFocusId;
}

public String getAutoFocusClientScript(){
 if (getClientFocusId() != null && mustExecuteAutoFocus){
  executeScript("autoFocus('" + getClientFocusId() + "');");
  mustExecuteAutoFocus = false;
 }
 return "";
}


3) js
function focus(focusId) {
 var f = document.getElementById(focusId + '::content'); 
 if(f == null) {
  f = document.getElementById(focusId);
 }
 if (f != null) {
  setTimeout("focusElement('" + f.id + "');", 100);
 }
}

function focusElement(elementId) {
    var c = document.getElementById(elementId);
    if (c != null) {
        c.focus();
        c.select();
    }
}

No comments:

Post a Comment