Rui
Rui

Reputation: 3673

How to invoke a form action only when clicking the submit button

When sending a jsf request without any query parameters to the page with the following jsf code:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf">
    <head>
        <title>Search for Word</title>
    </head>
    <body>
        <div>
            <form method="get" action="#{dictionary.search()}" id="search">
                <input jsf:id="keyword" value="#{dictionary.keyword}" />
            </form>
            <button type="submit" form="search" value="Submit">Submit</button>
        </div>
    </body>
</html>

the action dictionary.search() is always invoked even without clicking the submit button. However, the action is not expected to be invoked until the submit button is clicked.

Question: How to change the jsf code without any other extra tag libraries but only the provided jsf tab lib, i.e. the pass-through element so that the managed bean method dictionary.method() is invoked only when the submit button is clicked?

Upvotes: 0

Views: 840

Answers (2)

Rui
Rui

Reputation: 3673

I eventually found the answer myself:

            <form jsf:id="form">
                <input type="text" jsf:value="#{dictionary.keyword}" />
                <button jsf:action="#{dictionary.search}">Search</button>
            </form>

The nitty-gritty here is the generation of the equivalent component tree of that generated by h:commandButton

Based on the jsf 2.2 tutorial 8.5 HTML5-Friendly Markup,

To make an element that is not a JavaServer Faces element a pass-through element, specify at least one of its attributes using the http://xmlns.jcp.org/jsf namespace

the whole form has to passed through to jsf as a jsf component, the <form> element has to be like this <form jsf:id="form">, where the value of the id actually could be at random

The same goes with both the <input> and <button> element and, as to the <input> element the type attribute has to be assigned with a value, here is text

Upvotes: 2

Evgeni Enchev
Evgeni Enchev

Reputation: 552

First - your submit button must be inside the form tag. And then try to set the action on the button, not on the form to avoid the submit.

Hope this helps.

<body>
    <div>
        <h:form>
            ...
            <h:commandLink action="#{dictionary.search()}" value="Submit" />
        </h:form>
    </div>
</body>

Up to @BalusC comment my best is:

<form method="get" id="search" jsf:action="#{bean.search}" >
    <input jsf:id="keyword" value="#{bean.keyword}" />
    <input type="submit" jsf:action="#{bean.search}" value="SUBMIT"
</form>

But only putting jsf:action on both tags, form and input, was possible make it work.

May be @BalusC can show us the correct way.

Upvotes: 1

Related Questions