Parents :
<p:selectOneMenu id="parentList"
value="#{bean.selectedParent}"
converter="#{parentConverter}"
required="true">
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
<f:selectItems var="parent"
value="#{bean.parentList}"
itemLabel="#{parent.parentName}"
itemValue="#{parent}"/>
<p:ajax update="childrenList" listener="#{bean.setchildren}"/>
</p:selectOneMenu>
Children :
<p:selectOneMenu id="childrenList"
value="#{bean.selectedchild}"
converter="#{childConverter}"
required="true">
<f:selectItem itemLabel="Select" itemValue="#{null}"/>
<f:selectItems var="child"
value="#{bean.childrenList}"
itemLabel="#{child.childName}"
itemValue="#{child}"/>
</p:selectOneMenu>
The managed bean :
@Named
@ViewScoped
public class Bean implements Serializable {
@Inject
private Service service;
private Parent selectedParent;
private Child selectedChild;
private List<Parent> parentList;
private List<Child> childrenList;
private static final long serialVersionUID = 1L;
public Bean() {}
@PostConstruct
private void init() {
parentList = service.getParentList();
// Not necessary unless selectedParent is already available in edit mode.
if(selectedParent != null) {
childrenList = service.getChildrenListByParent(selectedParent);
}
}
public void setChildren() {
if(selectedParent != null) {
childrenList = service.getChildrenListByParent(selectedParent);
} else {
childrenList = null;
}
}
// Getters and setters.
}
The children list is to be populated based on their parent i.e. the children list should only contain children associated with a particular parent.
When the first parent in the parent list is selected, the children list should be reset to empty i.e. children should not be visible without their parent.
Since the parent list has a required field validator, it causes validation. When the first item in the parent list is selected, the children list will be prevented from being updated because of required="true"
. There is technically nothing wrong but existence of children without their parent may give end-users a bad experience.
What should happen is, when the first item in the parent list is selected, it should not cause validation i.e. the validation is to be skipped conditionally.
One way of doing this is to check either the selectedChild
or childrenList
itself is null/empty. Such as,
required="#{empty selectedChild or empty childrenList}"
But this does not appear to be a canonical way of skipping validation conditionally in such cases.
Does there exist a better way of skipping validation, when the first item in the parent list is selected so that the children list can be emptied as well along with the parent list (The validation should cause in all other cases. For example, when the form itself is submitted either synchronously or asynchronously)?