【问题标题】:Symfony2 Forms - Get editable elements in controllerSymfony2 Forms - 在控制器中获取可编辑元素
【发布时间】:2013-07-02 22:59:16
【问题描述】:

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

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

我可以在 JsonResponse 中传回值和输入类型并在 JavaScript 中渲染元素,但使用 Symfony2 表单渲染器会很有意义。

我希望返回如下内容:

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

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

【问题讨论】:

    标签: php symfony symfony-forms


    【解决方案1】:

    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
    

    并且模板调用了 {{ 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 有关于 how to customize form rendering 的文档。有了这个文档,你就会明白为什么需要通过 Twig。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多