4
我的形式類型具有收集場:的symfony 2,形式收集,驗證錯誤
$builder->add('affiliates', 'collection', array(
'type' => new AffiliateFormType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
));
在模板我有:
<table id="affiliates" >
<tr>
<th class="t1c0"></th>
<th class="t1c1" data-prototype="{{ form_widget(form.affiliates.vars.prototype.affiliate_name)|e }}">Name</th>
<th class="t1c2" data-prototype="{{ form_widget(form.affiliates.vars.prototype.affiliate_type_code)|e }}">Type</th>
<th class="t1c3" data-prototype="{{ form_widget(form.affiliates.vars.prototype.address)|e }}">Address</th>
</tr>
{% for affiliate in form.affiliates %}
<tr>
<td class="t1c0"><input type="button" class="delete_button" value="Delete"/></td>
<td class="t1c1">{{ form_widget(affiliate.affiliate_name) }}{{ form_errors(affiliate.affiliate_name) }}</td>
<td class="t1c2">{{ form_widget(affiliate.affiliate_type_code) }}{{ form_errors(affiliate.affiliate_type_code) }}</td>
<td class="t1c3">{{ form_widget(affiliate.address) }}{{ form_errors(affiliate.address) }}</td>
</tr>
{% endfor %}
</table>
<input type="button" class="add_button" value="Add line" onclick="addAffiliate();"/>
現在javasript代碼(與jquery)用於添加/刪除行是:
<script language="javascript">
var affiliatesCollection = $('table#affiliates');
$(document).ready(function(){
var rowCount = $('table#affiliates tr').length;
affiliatesCollection.data('index', rowCount - 1);
$('.delete_button').click(function(e) {
$(this).closest("tr").remove();
});
});
function addAffiliate() {
//get index
var index = affiliatesCollection.data('index');
affiliatesCollection.data('index', index + 1);
//add row
var cells = new Array();
var cell = $('<input type="button" class="delete_button" value="Delete"/>').click(function(){
$(this).closest("tr").remove();
});
var $cell = $('<td></td>').append(cell);
cells[0] = $cell;
for (var i = 1; i < 4; i++)
{
var prototype = $('th.t1c'.concat(i)).data('prototype');
var cell = prototype.replace(/__name__/g, index);
var $cell = $('<td></td>').append(cell);
cells[i] = $cell;
}
var $newRow = $('<tr></tr>').append(cells);
affiliatesCollection.append($newRow);
}
</script>
讓說名稱是必填字段。除了一種情況,上面的代碼工作正常:當一行被添加並刪除並再次添加時,刪除的索引不再可用,如第一行的索引= 1,第二行的索引= 3;並且當提交無效表單(例如名稱字段爲空)時,form.isValid()正確返回false,但驗證錯誤未顯示在其各自元素下方。有人可以幫我糾正這個問題嗎?謝謝。
我按照您的建議設置了error_bubbling = false,但問題仍然存在。如果模板中包含error_bubbling = true和{{form_errors(form)}},則驗證錯誤將顯示在全局範圍內。 Symfony似乎無法將這些錯誤與實際的收集輸入字段相關聯,但以某種方式仍然設法得到錯誤。我很確定它與索引被跳過有關。它發生在新行後面是另一個新行時,並且它們的索引不是按順序排列的(因爲它們之間的行被用戶刪除)。 – synergetic