Search code examples
symfonyfosrestbundle

Symfony form type inheritance problems


I am building an API using the FOSRestBundle and performing validation using the Types provided by Symfony.

The problem I am facing is that I am trying to find a way to flatten the form type inheritance model that was created when trying to prevent code duplication with inheritance within the form types. This was achieved using the guide on inherit data option.

e.g.

....

$builder->add('nested', new NestedType());

....

However this has an implication when trying to submit data to the API.

Currently:

{
    "type": {
        "key": "value",
        "nested": {
            "nested_key": "value"
        }
    }
}

What I am after:

{
    "type": {
        "key": "value",
        "nested_key": "value"
    }
}

Is there a way to achieve this without duplicating the code within the NestedType?


Solution

  • The solution that I ended up going with was to extend the NestedType for example:

    class TypeType extends NestedType
    {
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
        parent::buildForm($builder, $options);
        $builder
          ->add('key');
      }
    
      ....
    

    This is less than ideal though since on validation errors the errors in the extended class are hidden only bubbling the error and not what it is associated with.