5

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.

1
  • I come across this question lmost 9 months later, and I realise that my answer doesn't address your question! Updated my answer - better late than never, right? :) Commented Jun 23, 2016 at 21:06

3 Answers 3

12

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

If you need to get the JSON representation of the form object, you can get the entity object and encode it:

$jsonStr =json_encode($builder->getData());

Comments

0

Take a look on http://jmsyst.com/libs/serializer#installation and fosrestbundle

$view = $this->view( $form->createView() );
return $this->handleView( $view );

Does what you are looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.