Symfony2 Forms-在控制器中获取可编辑元素


Symfony2 Forms - Get editable elements in controller

我正在尝试设置一个用于编辑TaskType表单的内联可编辑表单。我正在通过ajax发送一个请求,该请求需要返回一个包含字段名称的json对象和呈现的html输入/选择/文本区域。

然而,我看不到提取渲染的html的方法。或者,有没有一种方法可以在twitch中将表单呈现为json(尽管这并不正确)?

我可以在JsonResponse中传回值和输入类型,并在JavaScript中呈现元素,但使用Symfony2 Form呈现器是有意义的。

我想退回这样的东西:

{ 
    title: "<input ... />",
    author: "<select ... ><option>...</option></select>"
    ...
}

如有任何帮助,我们将不胜感激!:)

Twig拥有每种类型字段的定义,因此我强烈建议使用Twig中的render函数。

你可以这样做:

$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(field)}}{{form_row(field)}}有一个调用(包括标签和错误消息)。

不确定这是否会执行良好,因此调用渲染函数一次可能比多次要好。

以下备选方案:

$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有关于如何自定义表单呈现的文档。有了这个医生,你就会明白为什么你需要通过Twig。