doubeng9407 2014-03-21 15:57
浏览 59
已采纳

Symfony 2中的表单,其字段根据外部数据在数量和目的上发生变化

I am building an application using Symfony 2, and one of the pages contains a large form, which has a number of fixed fields but also a number of fields whose presence and number depends entirely on related data taken from the DB. More specifically, the form poses a number of questions, and the questions themselves come from the DB, having different text and IDs. The answers need to be stored in the DB, linked to the questions.

I've read up on how Symfony handles forms (Basic Symfony Forms), including the relationship between a Form object and the data object backing it, creating Fields from the Form object, and validating input according to rules applied to the Form object.

Since I don't want a fixed Form object I looked at how you're meant to dynamically modify Forms (Dynamic Symfony Forms), but the examples there seem to be about choosing whether to show certain pre-defined fields, or controlling the options in the fields, not completely generating new fields from scratch, which is what I want.

I had a look at the Symfony page on Data Transformers, and it seemed relevant, but I couldn't quite get my head around how it would help me. They seem more about mapping a Form object to an Entity than mapping complex form submissions to a Form object.

I did see this SO answer where the object backing the Form object is just an array, which also seemed relevant: I thought that maybe the answer was to generate some anonymous object with the dynamic fields in, and then make a form from that, but I don't see how I'd set up Symfony validation on it, and my form is not completely different each time, so doesn't need to be entirely anonymous.

What is the best way to achieve this using Symfony 2, ideally without giving up such framework benefits as easy validation etc?

EDIT I hadn't heard of Symfony Form Collections before, and it looks like this might do what I want - each Question in my case would map to an individual subform object. I'll update again if I try it out successfully.

  • 写回答

2条回答 默认 最新

  • doufan9395 2014-09-17 22:40
    关注

    OK, in the end what I wanted wasn't a truly dynamic form (but thanks to @Cerad for that code), but one using Collections where the number of certain child form items was variable.

    So I essentially followed the Symfony Docs about Collections

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记