小枝擁有每種類型的字段的定義,因此我強烈建議使用Twig的渲染功能。
你可以做這樣的事情:
$formView = $this->createForm(new FormClass(), $entity)->createView(); // your form view
$json = array(); // initialize json array
foreach ($formView as $fieldKey => $field) {
$json['html'][$key] = $this->container
->get('templating')
->render('formField.html.twig', array('field' => $field));
}
$json['message'] = 'Success!'; // send a success or failure message
// encode the array above into json and return it
而且模板對通話{{form_widget(場)}}或{{form_row(場)}}(包括標籤和錯誤消息)。
不確定這是否會表現良好,所以最好多次調用渲染函數。下面
備選:
$formView = $this->createForm(new FormClass(), $entity)->createView(); // your form view
// parameters for the template
$params = array(
'form' => $formView
);
// render the form once
$renderedForm = $this->container
->get('templating')
->render('form.html.twig', $params);
$json = array(
'message' => 'Success!' // send a success or failure message,
'html' => $renderedForm,
);
// encode the array above into json and return it
Symfony的有大約how to customize form rendering文檔。有了這個文檔,你會明白你爲什麼需要通過Twig。