Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitted form values not updated in model when adding <f:ajax> to <h:commandButton>

I'm learning how to use ajax within jsf, I made a page that does actually nothing, an input text that is filled with a number, submitted to the server, call the setter for that element with the value submitted, and display the getter's value.

Here's the simple bean's code:

@ManagedBean(name="helper",eager=true)
public class HealthPlanHelper {


    String random = "1";

    public void setRandomize(String s){
        random = s;
                System.out.println("Calling setter");
    }

    public String getRandomize(){
        return random;
    }

}

And the jsf page:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">
<h:head></h:head>
<h:body>

    <h:form>
        <h:commandButton action="nothing">
            <f:ajax render="num"/>
        </h:commandButton>

        <h:inputText value="#{helper.randomize}" id="num"/>
    </h:form>

</h:body>
</html>

As you see, this is a request scoped bean, whenever I click the button the server shows that it creates an instance of the bean, but the setter method is never called, thus, the getter return always "1" as the value of the string.

When I remove the the setter is called normally.

like image 517
a.u.r Avatar asked Feb 16 '23 17:02

a.u.r


1 Answers

The <f:ajax> processes by default only the current component (read description of execute attribute). Basically, your code is exactly the same as this:

<h:form>
    <h:commandButton action="nothing">
        <f:ajax execute="@this" render="num"/>
    </h:commandButton>
    <h:inputText value="#{helper.randomize}" id="num"/>
</h:form>

In effects, only the <h:commandButton action> is been processed and the <h:inputText value> (and any other input field, if any) is completely ignored.

You need to change the execute attribute to explicitly specify components or sections you'd like to process during the ajax request. Usually, in order to process the entire form, @form is been used:

<h:form>
    <h:commandButton action="nothing">
        <f:ajax execute="@form" render="num"/>
    </h:commandButton>
    <h:inputText value="#{helper.randomize}" id="num"/>
</h:form>

See also:

  • Communication in JSF 2.0 - Ajax (asynchronous) POST form
  • commandButton/commandLink/ajax action/listener method not invoked or input value not updated (point 8)
  • Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
like image 68
BalusC Avatar answered Feb 18 '23 06:02

BalusC