PHPackages                             simplethings/form-serializer-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. simplethings/form-serializer-bundle

ActiveSymfony-bundle[Parsing &amp; Serialization](/categories/parsing)

simplethings/form-serializer-bundle
===================================

(De-)Serialization of Object-Graphs into XML/JSON based on Form Types

v0.2(13y ago)7919.6k18[12 issues](https://github.com/simplethings/SimpleThingsFormSerializerBundle/issues)[5 PRs](https://github.com/simplethings/SimpleThingsFormSerializerBundle/pulls)MITPHP

Since Jul 19Pushed 12y ago6 watchersCompare

[ Source](https://github.com/simplethings/SimpleThingsFormSerializerBundle)[ Packagist](https://packagist.org/packages/simplethings/form-serializer-bundle)[ RSS](/packages/simplethings-form-serializer-bundle/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (4)Versions (5)Used By (0)

FormSerializerBundle
====================

[](#formserializerbundle)

Bundle that helps solving the Serializer/Form component API missmatch. This missmatch leads to non-reusable code in controllers, bloating every application by reimplementing everything over and over again. Currently its nearly impossible to re-use REST-API calls and HTML/Form-based submits in the same controller action. Additionally all the current serializer components share a common flaw: They cannot deserialize (update) into existing object graphs. Updating object graphs is a problem the Form component already solves (perfectly!).

This bundle solves these issues by hooking into the Form Framework. It allows to implement serializers for objects, using form types. For deserializing it uses the exact same API as "usual" form requests.

The Form component is a very good serialization library, but up to now it only had one implementation: HTML Forms. This bundle adds support for hooking the Serializer Encoders into this process, XML and JSON supported by default.

New Form Options
----------------

[](#new-form-options)

Using this bundle you gain new form type options. The "form" field is overwritten to have the following additional configuration keys:

- `serialize_xml_name` - Specifies the root xml name or the list entry xml name of elements, depending on its definition on a parent or child element. (Default: entry)
- `serialize_xml_value` - If true, this field will be the xml value of the parent field. Useful if you have small embedded types that have some attributes and one value. (Default: false)
- `serialize_xml_attribute` - If true, this field will be rendered as attribute on the parent in xml, not as an element. (Default: false)
- `serialize_xml_inline` - If true, no collection wrapper element will be rendered for a collection of elements. If false, wrap all elements. (Default: true)
- `serialize_name` - Custom name of the element in serialized form if it should deviate from the default naming strategy of turning camel-case into underscore. (Default: false)
- `serialize_only` - If true the field will be removed from `FormView` and therefor only be present in the serialized data (json, xml)

Usage
-----

[](#usage)

This bundle defines a new service to serialize forms inside the Symfony DIC:

```
class UserController extends Controller
{
    public function showAction(User $user)
    {
        $serializer = $this->get('form_serializer');
        $xml = $serializer->serialize($user, new UserType(), 'xml');

        return new Response($xml, 200, array('Content-Type' => 'text/xml'));
    }
}
```

The API for the FormListener is documented on the `FormSerializerInterface` it implements:

```
interface FormSerializerInterface
{
    /**
     * Serialize a list of objects, where each element is serialized based on a
     * form type.
     *
     * @param array|Traversable $list
     * @param FormTypeInterface $type
     * @param string $format
     * @param string $xmlRootName
     *
     * @return string
     */
    public function serializeList($list, $type, $format, $xmlRootName = 'entries');

    /**
     * Serialize an object based on a form type, form builder or form instance.
     *
     * @param mixed $object
     * @param FormTypeInterface|FormBuilderInterface|FormInterface $typeBuilder
     * @param string $format
     *
     * @return string
     */
    public function serialize($object, $typeBuilder, $format);
}
```

The bundle also registers a Listener inside the form framework that binds XML and JSON requests onto a form. Just call `$form->bind($request)` as shown in the example below.

If you want to convert JMS Serializer based configuration to FormTypes you can use the command that is included:

```
php app/console simplethings:convert-jms-metadata "className"

```

Since JMS Serializer automatically builds metadata for every class, you can use this command to generate form types for any existing class for you.

Configuration
-------------

[](#configuration)

Default DIC (config.yml) configuration:

```
simple_things_form_serializer:
    include_root_in_json: false
    application_xml_root_name: ~
    naming_strategy: camel_case
    encoders:
        xml: true
        json: true
```

Dependency Injection tag named `simple_things_form_serializer.encoder` to add more encoders.

Example
-------

[](#example)

Take a usual form, extended with some details about serialization:

```
namespace Acme\DemoBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', 'text')
            ->add('email', 'email')
            ->add('country', 'entity')
            ->add('addresses', 'collection', array('type' => 'address', 'serialize_xml_name' => 'address'))
            ->add('created', 'datetime', array('read_only' => true))
        ;
    }

    public function getName()
    {
        return 'user';
    }

    public function setDefaultOptions(OptionsResolverInterface $options)
    {
        $options->setDefaults(array(
            'data_class' => 'Acme\DemoBundle\Entity\User',
            'serialize_xml_name' => 'user',
        ));
    }
}
```

Using the serializer:

```
$serializer = $this->get('form_serializer');
$data       = $serializer->serialize($user, new UserType(), 'xml');
```

Produces:

```

    beberlei
    kontakt@beberlei.de
    de

            Foostreet 1

    2012-07-10

```

Or if you use JSON:

```
{
    "user": {
        "username": "beberlei",
        "email": "kontakt@beberlei.de",
        "country": "de",
        "addresses": [
            {"street": "Foostreet 1"}
        ],
        "created": "2012-07-10"
    }
}
```

Deserializing will look familiar:

```
class UserController extends Controller
{
    /**
     * @Method("POST")
     */
    public function editAction(Request $request)
    {
        $em = $this->get('doctrine.orm.default_entity_manager');

        $user = $em->find('Acme\DemoBundle\Entity\User', $request->get('id'));
        $form = $this->createForm(new UserType(), $user);

        $form->bind($request);

        if ( ! $form->isValid()) {
            return $this->renderFormFailure("MyBundle:User:edit.html.twig", $form, array('user' => $user));
        }

        // do some business logic here

        $em->flush();

        return $this->formRedirect($form, $this->generateUrl('user_show', array('id' => $user->getId()), 201);
    }

    /* either render the form errors as xml/json or the html form again based on " _format" */
    public function renderFormFailure($template, FormInterface $form, $parameters)
    {
    }

    /* redirect OR 201 created, based on the "_format" */
    public function formRedirect()
    {
    }
}
```

This looks almost like a out of the book form request. The only thing different is that we have to use the "renderFormView" and "formRedirect" methods to generate response objects.

- `renderFormView` will decide based on the response format, what operation to perform.
    1. show a form, when format is html
    2. show a HTTP 405 error, when the passed form wasn't bound yet
    3. show a HTTP 412 pre-condition failed with the form errors serialized into xml or json.
- `formRedirect` will decide based on the response format:
    1. to redirect to the given url if its html (or config option `use_forwards = false`)
    2. to forward to the route if its xml or json (and config option `use_forwards = true`)

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance17

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

5096d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/892698bb1d3f6dae0e3a44abe3e26920ddb4eb000c6c583c87b4db5e5027e166?d=identicon)[beberlei](/maintainers/beberlei)

![](https://avatars.githubusercontent.com/u/470138?v=4)[David Badura](/maintainers/DavidBadura)[@DavidBadura](https://github.com/DavidBadura)

![](https://www.gravatar.com/avatar/9977780b392581daed6c7dd1a49ead2d3a9b0af03fa1bd174783fd293f6b9afe?d=identicon)[tobias.olry](/maintainers/tobias.olry)

---

Top Contributors

[![beberlei](https://avatars.githubusercontent.com/u/26936?v=4)](https://github.com/beberlei "beberlei (61 commits)")[![DavidBadura](https://avatars.githubusercontent.com/u/470138?v=4)](https://github.com/DavidBadura "DavidBadura (6 commits)")[![ccapndave](https://avatars.githubusercontent.com/u/297992?v=4)](https://github.com/ccapndave "ccapndave (4 commits)")[![henrikbjorn](https://avatars.githubusercontent.com/u/19725?v=4)](https://github.com/henrikbjorn "henrikbjorn (3 commits)")[![lsmith77](https://avatars.githubusercontent.com/u/300279?v=4)](https://github.com/lsmith77 "lsmith77 (3 commits)")[![Metabor](https://avatars.githubusercontent.com/u/2135064?v=4)](https://github.com/Metabor "Metabor (2 commits)")[![pborreli](https://avatars.githubusercontent.com/u/77759?v=4)](https://github.com/pborreli "pborreli (1 commits)")[![Adel-E](https://avatars.githubusercontent.com/u/285700?v=4)](https://github.com/Adel-E "Adel-E (1 commits)")

### Embed Badge

![Health badge](/badges/simplethings-form-serializer-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/simplethings-form-serializer-bundle/health.svg)](https://phpackages.com/packages/simplethings-form-serializer-bundle)
```

###  Alternatives

[easycorp/easyadmin-bundle

Admin generator for Symfony applications

4.3k17.9M388](/packages/easycorp-easyadmin-bundle)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k5.9M731](/packages/sylius-sylius)[api-platform/core

Build a fully-featured hypermedia or GraphQL API in minutes!

2.6k51.2M334](/packages/api-platform-core)[oro/platform

Business Application Platform (BAP)

645143.5k114](/packages/oro-platform)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

21866.0M1.7k](/packages/drupal-core)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M560](/packages/shopware-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
