Spring is not showing validation error for Dynamically generated Form Id

326 views Asked by At

Spring validation works fine for a form with static id. But in my scenario forms are generated dynamically on frontend.

For Example - My form bean is - GenericQuestionnaireForm so if i have the form element as below

<form:form method="post" modelAttribute="genericQuestionnaireForm" action="/save-generic-questionnaire">

validation works fine and the errors are correctly displayed.

But I have to capture the form values for different products so I am generating different forms with unique id by attaching the form name with the product number.

<form:form method="post" modelAttribute="product1_genericQuestionnaireForm"  action="/save-generic-questionnaire">

when I submit this form to my controller method the BindingResult are getting attached to the genericQuestionnaireForm form object due to which the errors are not getting displayed on front end.

@RequestMapping(value = "/save-generic-questionnaire", method = RequestMethod.POST)
public String saveQuestionnaire(@Valid final GenericQuestionnaireForm genericQuestForm,final BindingResult bindingResult,  final Model model,
                                    final RedirectAttributes redirectModel, final HttpServletRequest request) throws CMSItemNotFoundException{

    if(genericQuestForm != null) {

        genericQuestionnaireFormValidator.validate(genericQuestForm, bindingResult);
        if (bindingResult.hasErrors()) 
        {  return //to the front end..}
}

My query is - Is there a way to attach the BindingResult to the dynamic form Id in order to show the generated errors. Or is there a better way to do form validation in this scenario?

1

There are 1 answers

0
SeaBiscuit On BEST ANSWER
<<form:form:form method="post" modelAttribute="genericQuestionnaireForm" action="/save-generic-questionnaire" >
        <form:hidden path="id"/>
.................
</form:form>

modelAttribute attribute always remains the same.

@ModelAttribute("genericQuestionnaireForm")
public genericQuestionnaireForm getgenericQuestionnaireForm(){
    return new genericQuestionnaireForm();
}

RequestMapping(value = "/save-generic-questionnaire", method =   
RequestMethod.POST)

public String saveQuestionnaire(@Valid final GenericQuestionnaireForm genericQuestForm, BindingResult bindingResult.....

for identifing different products just use hidden id.