1

I want to set focus on inputText field in JSF when there is a validation error on that particular inputText. How can I implement this?

I thought validatorMessage on the inputText would do this out of the box but it appears not.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
damien535
  • 627
  • 3
  • 14
  • 31

1 Answers1

2

There is no such default behaviour. You need to implement it yourself or use a 3rd party library for the job. Basically, during the render response you need to walk through the submitted form for all UIInput components and find the first one whose isValid() returns false and then store its client ID in the request map so that you can print it as a JS variable.

form.visitTree(VisitContext.createVisitContext(), new VisitCallback() {

    @Override
    public VisitResult visit(VisitContext context, UIComponent component) {
        if (component instanceof UIInput && !((UIInput) component).isValid()) {
            context.getFacesContext().getExternalContext().getRequestMap()
                .put("focus", component.getClientId(context.getFacesContext()));
            return VisitResult.COMPLETE;
        }

        return VisitResult.ACCEPT;
    }
});

Then you can use the following script to set the focus:

<h:outputScript target="body">
    var focus = '#{focus}';

    if (focus) {
        document.getElementById(focus).focus();
    }
</h:outputScript>

The JSF utility library OmniFaces has a reuseable component for this, the <o:highlight> (source code here and showcase demo here). It additionally also sets a styleclass on the invalidated inputs so that you can specify for example a different background color by CSS.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for the solutions BalusC. Tried implementing what you have detailed above but unfortunatley requiredMessage/validatorMessage appear to be thrown before my code in the render response is reached. Any ideas on how to get around this? Thanks for your help – damien535 Jun 27 '12 at 13:50
  • As told in my answer, you need to perform the job during render response phase, not inside some command button action method during invoke action phase. You can use a custom component (like OmniFaces did) or a `PhaseListener` for this. – BalusC Jun 27 '12 at 13:56
  • Created a PhaseListener and tried placing similar code to yours in the afterPhase method and in the beforePhase method, the getPhaseId method also set to return RENDER_RESPONSE.Unfortunately my code only gets hit when the page is loaded, and does not get hit again when my submit button is clicked.Do you know where I may have gone wrong here? Thanks for your time. – damien535 Jun 28 '12 at 12:24
  • It should be done in `beforePhase()`. It should definitely be called for every request. Perhaps you interpreted the problem wrong (i.e. you didn't check if the method was actually called by a debugger/logger but you instead checked if the result was what you expected). – BalusC Jun 28 '12 at 12:28
  • Ah my bad, code was completely out of sync so my debugging was all wrong. In my code I do the following: FacesContext facesContext = event.getFacesContext(); UIComponent inputField = facesContext.getViewRoot(); When I then inspect the cast in the if condition you provided me with it gives a ClassCastException(UIPortletViewRoot to UIInput) so that appears to be my problem. – damien535 Jun 28 '12 at 12:44
  • You should be doing an `instanceof` check before. By the way, the `getViewRoot()` doesn't return the input field, but the view root. Fix your misleading variable names or it'll only confuse yourself and future code maintainers. – BalusC Jun 28 '12 at 12:45
  • I do, I only discovered this when inspecting the value in debug. It never actually gets to throw the ClassCast because of the instanceof check. However it always fails this validation so never get's inside ot set the focus. – damien535 Jun 28 '12 at 12:49
  • So I just tested what I've implemented(Changed the incorrect variable name too). Put a break point in the beforePhase method and this is hit when navigating to the page with my form, but no hit when I click to submit my form. – damien535 Jun 28 '12 at 14:48
  • Needed to turn off client side validation in order to get this to work(jsValidation="false").Nice answer and cheers for all your help BalusC! – damien535 Jul 09 '12 at 15:49