Symfony2形式为JSON结构 [英] Symfony2 form to JSON structure

查看:121
本文介绍了Symfony2形式为JSON结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Symfony2表单如何转换为JSON数据结构?例如:

  

$ builder
- > add('name','text')
- > add('password','password')
;

会导致类似的情况:

 {
字段:{
名称:{
类型:'text'
},
密码:{
类型:'密码'
}
}
}

$ form = $ this-> createForm(new FormType(),new Entity())之后遍历每个元素并没有帮助,找不到某些属性可以在表单构建器中定义。

解决方案

我假设你想在控制器中获得这些信息,在这种情况下,您可以很容易地从表单对象中获取底层实体,如下所示:

  $ entity = $ form-> ;的getData(); 

此时,您可以手动将所需的字段拖放到数组中,并将 json_encode(),或者...实现 JsonSerializable 接口,然后直接使用 json_encode()对象本身。



例如:

 <?php 

namespace FooApp / BarBundle /实体;

使用JsonSerializable;

class Baz实现了JsonSerializable
{
private $ name;
私人$密码;

// ...

函数jsonSerialize()
{
return [
'fields'=> [
'name'=> ['type'=> $ this-> name],
'password'=> ['type'=> $ this->密码],
],
];


然后,在你的控制器中:

  $ entity = $ form-> getData(); 
$ json = json_encode($ entity);

调用 json_encode()会自动调用<


























$ strong>更新2016年6月23日



我偶然发现了这个问题 - 并且...我意识到我没有回答您的实际题。

您不希望将表单的底层实体转换为JSON,而是希望将表单结构表示为数据。我很抱歉误会 - 希望我可以通过更新来纠正它。



这是一个概念验证,应该适用于非嵌套形式(尽管它应该直截了当地为这种情况创建递归版本或其他东西)。但是,假设已经实例化了一个表单,其中包含字段 name password ,如下所示:

  $ form = $ this-> createForm(FooType :: class,$ foo); 

然后应该遍历实例并派生出结构的表示;例如:

  $ fields = ['fields'=> []]; 

foreach($ form-> all()as $ field){
$ name = $ field-> getName();
$ type = $ field-> getConfig() - > getType() - > getBlockPrefix();
$ fields ['fields'] [$ name] = ['type'=> $类型]
}

echo json_encode($ fields,JSON_PRETTY_PRINT);

收益率:

 < 
字段:{
name:{
type:text
},
password:{
type:password
}
}
}

希望这有助于:)

How can the Symfony2 form be transformed to JSON data structure? Looking for proper bundle gave me no results;

Example:

$builder
    ->add('name', 'text')
    ->add('password', 'password')
;

Would result in something like that:

{
    fields: {
        name: {
            type: 'text'
        },
        password: {
            type: 'password'
        }
    }
}

Iterating over each element in form after $form = $this->createForm(new FormType(), new Entity()) was not helpful, could not find some properties that could be defined in form builder.

解决方案

I assume that you want to get this information in a controller once you have posted the form, in which case you can easily get the underlying entity from the form object, like so:

$entity = $form->getData();

At this point you can either manually pull out the fields you want into an array and json_encode() that, or... implement the JsonSerializable interface in your entity and then directly json_encode() the object itself.

For example:

<?php

namespace FooApp/BarBundle/Entity;

use JsonSerializable;

class Baz implements JsonSerializable
{
    private $name;
    private $password;

    // ...

    function jsonSerialize()
    {
        return [
            'fields' => [
                'name'     => ['type' => $this->name],
                'password' => ['type' => $this->password],
            ],
        ];
    }
}

Then, in your controller:

$entity = $form->getData();
$json = json_encode($entity);

Calling json_encode() will automatically invoke Baz::jsonSerialize() and return the array structure you defined, which in turn is JSON-encoded.

Update 2016-06-23

I happened across this question again by chance - and... I realise that I didn't answer your actual question.

You didn't want to convert the form's underlying entity to JSON - instead you want to represent form structure as data. My apologies for misunderstanding - hopefully I can rectify that with an update.

This is a proof-of-concept that should work for a non-nested form (although it should be straightforward to create a recursive version or something for that case). But, assuming a scenario where you have instantiated a form, comprising of fields name and password, like so:

$form = $this->createForm(FooType::class, $foo);

It should then possible to iterate over the instance and derive a representation of the structure; e.g:

$fields = ['fields' => []];

foreach ($form->all() as $field) {
    $name = $field->getName();
    $type = $field->getConfig()->getType()->getBlockPrefix();
    $fields['fields'][$name] = ['type' => $type];
}

echo json_encode($fields, JSON_PRETTY_PRINT);

Yields:

{
    "fields": {
        "name": {
            "type": "text"
        },
        "password": {
            "type": "password"
        }
    }
}

Hope this helps :)

这篇关于Symfony2形式为JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆