Reputation: 4338
Assume we have a form. One p:inputText
visible but user can add many more using p:commandButton
. All this values have to be provided when submitting with another p:commandButton
. Issue arises when user tries to add more than one empty input fields. All of them are marked required="true"
so validation error appears when one field is empty and user try to add another.
The best would be to allow to add as many fields as user needs, then fill them in and submit.
JSF:
<h:form id="myForm">
<p:commandButton value="add" actionListener="#{testBean.addNewItem()}" update="@form"/>
<p:commandButton value="done" update="@form,:p"/>
<br/>
<ui:repeat value="#{testBean.list}" var="l">
<p:inputText value="#{l.name}" required="true"/>
<br/>
</ui:repeat>
</h:form>
<p:messages autoUpdate="true"/>
<p:panel id="p">
#{testBean.list}
</p:panel>
Backing bean does nothing fancy. Only provides getter and setter for list. It also adds empty string to the list.
@ManagedBean
@ViewScoped
public class TestBean implements Serializable {
private List<Item> list = new ArrayList<Item>();
public List<Item> getList() { return list; }
public void setList(List<Item> list) { this.list = list; }
public void addNewItem() { list.add(new Item()); }
}
I could:
immediate="true"
for adding button. Validation is not a problem now but it causes all values that was filled in but not submitted to disappear. And I need to update @form
because only then newly added fields will be rendered by ui:repeat
.process="@this"
for adding button. Unfortunately that didn't change a thing. Input field values are not processed, but form needs to be updated. I am loosing not submitted values as above.What am I missing? Is there any workaround?
Upvotes: 2
Views: 5587
Reputation: 1109570
Just let the required
attribute check if the "done" button is pressed. The button's own client ID is present as a request parameter if that's the case. Request parameters are available by #{param}
mapping. You can use button's binding
attribute to bind the physical component to the view so that you can grab its UIComponent#getClientId()
elsewhere. Finally just do the boolean logic.
E.g.
<p:commandButton binding="#{done}" ... />
...
<p:inputText ... required="#{not empty param[done.clientId]}" />
Upvotes: 3
Reputation: 59
Will something like this work?
<p:inputText value="#{l.name}" required="#{l.name != null ? true : false}"/>
This will enable the newly added inputText components to not be required but enforce the items already in the list to be required.
Upvotes: -1