我覺得你做這樣很難。
對於這個問題,我會創建2個窗體(FormChildA,FormChildB)相應的字段。
因爲你使用JavaScript無論如何,只是一個選擇渲染頁面,並獲得與阿賈克斯的形式:
<div id="select-type">
<button value="child_a" type="button">Select ChildA</button>
<button value="child_b" type="button">Select ChildB</button>
</div>
<div id="form-container"></div>
<script>
$('#select-type button').on('click', function(event) {
event.preventDefault();
$.get('path/to/get_ajax_form', {type: $(this).val()}, function(data) {
$('#form-container').html(data);
});
});
</script>
創建一個控制器方法來檢索形式:
public function getAjaxFormAction()
{
$type = $this->get('request')->query->get('type');
switch($type) {
case 'child_a':
$form = $this->createForm(new FormChildA, new ChildA);
break;
case 'child_b':
$form = $this->createForm(new FormChildB, new ChildB);
break;
}
return $this->render('AcmeBundle:Forms:_type_form.html.twig', array(
'form' => $form->createView(),
'type' => $type,
));
}
添加到每個窗體。與窗體類型值的隱藏字段,
這種方式可以驗證在一種方法(如你檢索它們相同的方式)這些形式。
這使得它更容易修改,並分別驗證每個表格!
你是對的簡單。我只看到一個可能出現的問題在這種方法中,如果用戶更改類型有後的表格填寫,他必須重新填寫表格,不過,我想我會按照這個方法,感謝您的想法 – Zeux
沒問題,你關於變化形式問題是正確的。但也許這可以通過使用[sisyphus.js](http://simsalabim.github.com/sisyphus/)來解決。如果您給相同的字段使用相同的名稱,則每次用戶選擇其他表單時,都可以用sisyphus更新您的表單。 (只是一個想法) – Gintro