Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a label in JSF (Primefaces)

I have a JSF page with a button and a label. When the user presses the simulateYearButton button, the value displayed in the label yearLabel should be incremented.

The form with the button and the label looks like this:

    <h:form>
        <p:commandButton value="Заресетить" id="resetButton"
            actionListener="#{entryPage.resetButtonAction}" />

        <p:commandButton value="Просимулировать год" id="simulateYearButton"
            actionListener="#{entryPage.simulateYearButtonAction}">
            <f:ajax event="click" render="yearLabel" />
        </p:commandButton>


        <h:outputLabel id="yearLabelLabel" for="yearLabel" value="Год:" />
        <h:outputLabel id="yearLabel" value="#{entryPage.yearLabel}"
            style="font-weight:bold" />
    </h:form>

Code of the entryPage bean:

@ManagedBean(name = "entryPage")
@RequestScoped
public class EntryPageController {
    ...
    private int year;
    private String yearLabel;

    @PostConstruct
    public void init()
    {
        this.yearLabel = "2012";
    }

    ...

    public void simulateYearButtonAction() {
        LOGGER.debug("EntryPageController.simulateYearButtonAction");
        this.year++;
        this.yearLabel = Integer.toString(this.year);
    }

    public String getYearLabel() {
        return yearLabel;
    }
}

When I press the simulateYearButton, the method simulateYearButtonAction is executed (I see the log message in the output), but the label is not updated.

How should I modify the code so that the label is updated, when I press the button?

like image 868
Dmitrii Pisarenko Avatar asked Mar 24 '26 10:03

Dmitrii Pisarenko


1 Answers

New answer:

 <p:commandButton value="Просимулировать год" id="simulateYearButton"
      actionListener="#{entryPage.simulateYearButtonAction}" update="yearLabel">
 </p:commandButton>

Because commandbutton is ajaxed by default.

Next, you need to make the bean @ViewScoped. Next, you need to assign to year the value of yearLabel :

 @PostConstruct
public void init()
{
    this.yearLabel = "2012";
    this.year = Integer.parseInt(yearLabel);
}
like image 186
Dragos Bulugean Avatar answered Mar 27 '26 00:03

Dragos Bulugean