1

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

但是,我看不到提取呈现的 html 的方法。或者,有没有办法在 twig 中将表单呈现为 json(尽管这看起来不对)?

我可以只传回 a 中的值和输入类型,JsonResponse然后在 JavaScript 中渲染元素,但使用 Symfony2 表单渲染器是有意义的。

我希望返回这样的东西:

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

任何帮助,将不胜感激!:)

4

1 回答 1

0

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.

于 2013-07-02T14:52:02.607 回答