Spring Web Flow - Multiple forms on page - validat

2019-07-16 07:04发布

问题:

I am using Spring Web Flow 2.3 and I have a page that has two forms on it that transition to different places depending on which is submitted. To accomplish this, I have one composite model object for my view-state that holds the two forms inside. The problem I am seeing is that if transition A is fired, I only want to validate form A, and likewise with form B - only want to validate B if B transition fired. I am not sure how to indicate which form to validate. View state that is validating the entire compositeForm for each transition:

<view-state model="compositeForm">
    <transition on="formAsubmit" to="formApage" validate="true"/>
    <transition on="formBsubmit" to="formBpage" validate="true"/>
</view-state>

Does anyone know how I can trigger a custom validator to validate differently depending on which transition was fired?

Thanks for you help.

Steve

回答1:

I don't know about a custom validator for each, but within your validation method, I think you could use the RequestContextHolder.getRequestContext() to getCurrentTransition() or getCurrentEvent() and compare manually to the getId() value.



回答2:

What I ended up doing was to manually trigger my validation when form B was submitted and transition to a decision-state that checks if there were validation errors. It's a little ugly, but I feel like it's the best way:

<view-state id="start" model="compositeForm">
    <transition on="formAsubmit" to="pageA" validate="true"/>
    <transition on="formBsubmit" to="isFormBValid" validate="false">
        <evaluate expression="formBValidator.validate(compositeForm.formB, messageContext)"/>
    </transition
</view-state>

<decision-state id="isFormBValid">
    <if test="messageContext.hasErrorMessages()" then="start" else="pageB"/>
</decision-state>


回答3:

This is not the best solution, but at least is solves the problem. This is how I obtained my transition id and view-state id in vlaidator.

Transition id

RequestContextHolder.getRequestContext().getFlowExecutionContext().getActiveSession().getState().getId();

view-state id

 RequestContextHolder.getRequestContext().getFlowExecutionContext().getActiveSession().getState().getId();