I'm writing a validator method in JSF 2. I have a ui:repeat element in my page that renders a list of items. Each item has a date property, and I need to ensure the dates correspond to each other in a specific sequence, e.g. the date of the last item in the list doesn't come before the date of the first item. I was trying to get all the child elements inside the ui:repeat and iterate over them to do the comparison, but I don't really know where to start. I've seen how to get a specific element by ID:
UIInput input = (UIInput) context.getViewRoot().findComponent(elementId);
However, within the ui:repeat the ID values are made unique by JSF, so I don't know what they are at compile time. Furthermore, at compile time I don't know how many items there will be in the list.
I've looked at the Javadoc for UIViewRoot and other associated classes, and have tried a couple things, but I'm getting errors, things aren't working, and I don't really know if I'm even close to getting anywhere. I'm leaving the code of my attempts out of this post, becuase they're probably a joke.
There's physically only one
UIInputcomponent whose state changes depending on the current iteration round ofUIRepeat. It's available by just its client ID without theUIRepeatindex:findComponent("formId:inputId")(theUIRepeatindex is only of significance in the client side). However, when the component is programmatically been accessed outside the context ofUIRepeatthis way, then it'll indeed return a seemingly empty state.In order to visit the
UIInputcomponent in all those states as they are inside theUIRepeatand collect their values, you need to runUIComponent#visitTree()on theUIRepeat.Here's a kickoff example:
With this
validateOrder()method (again, just a kickoff example, this approach naively assumes that there's only oneUIInputcomponent in the repeater):Note that it visits the tree twice; first time to collect the values and second time to mark those inputs invalid. Also note that this very specific requirement can't be done with a standard JSF validator. You can't attach a
<f:validator>on<ui:repeat>. Attaching it on<h:inputText>is theoretically possible, but it would cause the very same validator to run as many times as the amount of repeated items, which doens't make sense. Also, the validator would need to takegetSubmittedValue()vsgetValue()into account this way.OmniFaces has an
<o:validateOrder>component which does a similar thing on fixed components, but it isn't designed for usage in dynamically repeated components.