简体   繁体   English

Symfony2 FormType转换为JSON

[英]Symfony2 FormType to JSON

Is it possible somehow to serialize Symfony2 FormType into JSON? 是否可以将Symfony2 FormType序列化为JSON? I have the following Type for User form. 我具有以下“用户类型”表单。

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array('label' => 'Name'))
            ->add('surname', 'text', array('label' => 'Surname'))
            ->add('username', 'text', array('label' => 'Username'))
            ->add('email', 'text', array('label' => 'Email'))
            ->add('isAdmin', 'checkbox', array('label' => 'Admin'));
    }
    ...
}

Possible to get the following or similar JSON format using Symfony2 itself, or I will need my custom parser? 可以使用Symfony2本身获取以下或类似的JSON格式,还是需要自定义解析器?

{
    "name": {
        "type": "text",
        "label": "Name"
    },
    "surname": { 
        "type": "text",
        "label": "Surname"
    },
    "username": {
        "type": "text",
        "label": "Username"
    },
    "email": {
        "type":"text",
        "label":"Email"
    },
    "isAdmin": {
        "type": "checkbox",
        "label" : "Admin"
     }
}

You could implement a form theme that would output your widgets any way you want to. 您可以实现一个表单主题,该主题将以您想要的任何方式输出窗口小部件。 Here's a link to Symfony documentation that explains how to create and apply form themes. 这是Symfony文档链接,该文档说明了如何创建和应用表单主题。

However, if you're implementing an API (otherwise why would you need to get the form as JSON?), you should definitely take a look at FOSRestBundle , as it implements form handling and serialization. 但是,如果要实现API(否则为什么需要将表单作为JSON?),则一定要看看FOSRestBundle ,因为它实现了表单处理和序列化。

看起来您可能正在寻找类似Liform捆绑包的东西,该捆绑包允许您从Symfony表单生成JSON模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM