私のフォーム タイプにはコレクション フィールドがあります。
$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 つのケースを除いて正常に動作します。行が追加され、削除され、再度追加されると、最初の行のインデックス = 1、2 番目の行のインデックス = 3 のように、削除されたインデックスは使用できなくなります。無効なフォームが送信された場合 (たとえば、名前フィールドが空の場合)、form.isValid() は正しく false を返しますが、検証エラーはそれぞれの要素の下に表示されません。誰かが問題を修正するのを手伝ってくれますか? ありがとうございました。