2017-04-14 17 views
0

我想添加一個輸入字段在按鈕單擊後,我收到一個異常如下:.IllegalStateException: Neither BindingResult nor plain target object for bean name 'name' available as request attribute
我假設它這樣做,因爲它不能保證有提交時將結果綁定的對象?有沒有辦法解決?或者我無法動態加載字段?從按鈕點擊事件動態加載一個<form:input> - 春天MVC

這是我的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. 
} 

我可以動態輸入一個標準的輸入字段,但我不能爲我的控制器分配一個路徑。

編輯 -

如果我包裹在與目標對象中聲明的錯誤消失像這樣:

<form:form commandName="newIngredients"> <form:input path="name" /> <form:input path="amount"/> <form:input path="unit"/></form:form> 

這消除了錯誤,但自動生成的輸入內的輸入不要通過控制器。

+0

是,當你爲你的輸入字段設置不同的名稱(例如,你不重名引發甚至例外)? –

+0

是的,是的。 重複的名稱正在返回由''分隔的連接字符串, – Chris

回答

0

我已經使用.clone()方法解決了這個問題,使用我發現的代碼片段here我已經通過簡單地更改被克隆的html來適應它,以支持Spring窗體標籤。

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; 
    }); 
});