Twig 拥有每种类型字段的定义,因此我强烈建议使用 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
And the template has a call on {{ form_widget(field) }} or {{ form_row(field) }} (to include label and error message).
Not sure if this will perform well so it's probably better to call the render function once than multiple times.
Alternative below:
$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 has documentation about how to customize form rendering. With this doc, you will understand why you need to go through Twig.