NeplatnyUdaj
NeplatnyUdaj

Reputation: 6242

Switch to tab in tabView with invalid input

The problem is really simple. I have a tabview with multiple tabs:

<h:form>
    <p:tabView id="tabView">
        <p:tab>
            <p:inputText required="true"></p:inputText>
        </p:tab>
        <p:tab>
            <p:inputText required="true"></p:inputText>
        </p:tab>
    </p:tabView>
    <p:commandButton value="submit" action="#{myBB.submit}" update="tabView"/>
</h:form>

What I would like is to switch to the tab with missing field when the client-side validation fails. I thought that this must be a common use-case for form in tabs, but I cannot find any solution.

The only thing I can think of is call some oncomplete action on the submit button which would go through the DOM and find the invalid components, but it seems overly complicated for a thing which I believe should be default behavior.

Upvotes: 1

Views: 738

Answers (1)

NeplatnyUdaj
NeplatnyUdaj

Reputation: 6242

So I've found a way to do that. After the ajax completes, I created an oncomplete method to search through the tabs and select the correct one. First I had to modify the source a bit(just added ids and widgetVar):

<h:form>
  <p:tabView id="tabView" widgetVar="tabViewWv">
    <p:tab id="tab1">
        <p:inputText required="true"></p:inputText>
    </p:tab>
    <p:tab id="tab2">
        <p:inputText required="true"></p:inputText>
    </p:tab>
  </p:tabView>
  <p:commandButton ... oncomplete="switchToInvalidTab()"/>
</h:form>

and the javascript:

    function switchToInvalidTab() {
        var lastIndex = 0;
        var tabParent = '#mainForm\\:tabView\\:';
        var tabs = ['tab1', 'tab2']; //can add more, but the order must be the same as in form
        tabs.some(function (tabName){
            if ($(tabParent + tabName)) { //tab may not exist in my app
                if ($(tabParent + tabName).find(':input').hasClass('ui-state-error')){
                    PF('tabViewWv').select(lastIndex);
                    return true;
                }
                lastIndex++;
            }
            return false;
        });
    }

There are more tabs in my app and some of them doesn exist sometimes and this code works for all cases. Maybe it helps someone

Upvotes: 1

Related Questions