3

I have two entity classes in a unidirectional many-to-one relation and two fos rest controllers that take care of creating, fetching, updating, and deleting each of them using their own form types (as described here).

When creating a new entity on the "many" side of the relation (Topic), I want to link it with an existing entity on the "one" side (Category). The form type of Topic looks like this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('category', 'entity', array('class' => 'MyNiceBundle:Category', 'property' => 'id'))
    ;
}

but it doesn't take my post request of the form

{"my_form":{"category":{"id":2, "aProperty":"bla"}}}

or

{"my_form":{"category":{"id":2}}}

The error I get is "category":{"errors":["This value is not valid."]}}

In the end, I found out that sending

{"my_form":{"category":2}}

actually worked. But it's a bit annoying because when I fetch Topics using GET, I get

{"id":1, "category":{"id":2, "aProperty":"bla"}}

and not

{"id":1, "category":2}

so before making an update with PUT, I have to overwrite the category property with its ID...

I'm sure there is a better way to do this. Any advice?

Naoki
  • 49
  • 6

2 Answers2

0

I would change the PUT controller on the rest server side to make it compatible with both methods :

{"my_form":{"category":2}}

and

{"my_form":{"category":{"id":2, "aProperty":"bla"}}}

If you do that, you won't have to worry about the category object, and everything would be done by the put controller, inject in the form data, before calling isValid() method the right syntaxe for the formType and Voilà ! At least, I would do so.

Taytay
  • 82
  • 7
  • Well, I guess in that case I would have to tamper with the $_POST data before calling $form->bind($this->getRequest()). The problem is that the binding doesn't work correctly with {"my_form":{"category":{"id":2}}}. I wonder if there's a more elegant way. – Naoki Oct 24 '13 at 13:17
  • Yes, coding your own EntityToID Transformer, sorry I meant compatible with {"my_form":{"category":2}}, I've updated my answer – Taytay Oct 24 '13 at 13:20
  • But what I need is an EntityToArray transformer, not an EntityToID transformer. As there is no field type "Array", I don't know how to solve this. – Naoki Nov 21 '13 at 10:26
  • {"id":2, "aProperty": "bla"} <=> category object – Naoki Nov 21 '13 at 10:27
0

Just opened an issue at the official repo: https://github.com/FriendsOfSymfony/FOSRestBundle/issues/984

Will extend this answer as soon as a proper solution is suggested.

Marc Juchli
  • 2,240
  • 24
  • 20