我试图在点击按钮时添加输入字段,我收到如下异常:.IllegalStateException: Neither BindingResult nor plain target object for bean name 'name' available as request attribute
我假设它正在这样做,因为它不能保证有一个对象将结果绑定到提交?有没有办法解决?或者我不可能动态加载字段?
这是我的HTML,我现在只是在玩这个概念所以它是最低限度的
<input type="button" id="more_ingredients" onclick="add_ingredients();" value="add more">
<form:form commandName="newIngredients" id="form">
<div id="wrapper">
<form:input path="name"/>
<form:input path="amount"/>
<form:input path="unit"/>
<br>
<form:input path="name"/>
<form:input path="amount"/>
<form:input path="unit"/>
<br>
</div>
<form:button type="submit">Submit</form:button>
</form:form>
这是我的JS
function add_ingredients() {
document.getElementById('form').innerHTML += '<form:input path="name /> <form:input path="amount"/> <form:input path="unit"/>';
//The exception is being triggered by the above line, if I remove the 'form:' tag, the error will disappear.
}
我可以动态输入标准输入字段,但是我无法为控制器分配路径。
修改
如果我用声明的目标对象包装a,那么错误就会消失:
<form:form commandName="newIngredients"> <form:input path="name" /> <form:input path="amount"/> <form:input path="unit"/></form:form>
这会消除错误,但自动生成的输入内的输入不会传递给控制器。
答案 0 :(得分:0)
我使用.clone()方法解决了这个问题,使用我发现here 的代码片段我通过简单地更改被克隆的html来略微调整它以支持spring form标签。
HTML:
<form:form commandName="newIngredients">
<div id="dynamic_ingredients">
<a id="add-ingredient" href="#">Add Another Ingredient +</a>
<div class="ingredient_field">
<form:input path="name"/>
<form:input path="amount"/>
<form:input path="unit"/>
</div>
</div>
</form:form>
jQuery:
$(document).ready(function(){
//the click function does not seem to be working in the example, so I have replaced it with this.
$(document).on('click', '.icon-delete', function(){
$(this).parent().remove();
});
//Keep a single clone of the original
var clonedField = $('.ingredient_field').clone(),
main = $('#dynamic_ingredients');
// Add in the delete <a>
$('<a>', {
text: 'Remove Step',
class: 'icon-delete',
href: '#'
}).appendTo(clonedField);
// Clone the cloned original and append it back to the list
$('#add-ingredient').click(function() {
main.append(clonedField.clone());
return false;
});
});