Symfony - collection of form types - how to set objects by ID

I am working on a Symfony project (API) and it uses the JSMSerializer, so all data sent as useful information is in json format.

Then I have two objects, for example User and Devices. I have two types of forms for each of them, and although the relationship between the two is OneToMany, in the first FormType the “devices” field is a collection of DeviceType forms.

When you add, simply, you should post something like this

{
  "user": {
    "name": "John",
    "devices": [
      {
        "os": "Android",
        "color": "red"
      },
      {
        "os": "Android",
        "color": "blue"
      }
    ]
  }
}

Everithing works just fine. Objects are saved in db.

When updating, the same payload can be sent in the same order with some changed data, as shown

{
  "user": {
    "name": "John",
    "devices": [
      {
        "os": "Android",
        "color": "redish"
      },
      {
        "os": "Android",
        "color": "blueish"
      }
    ]
  }
}

and symfony does its magic.

, . .

: , symfony/doctrine , ?

-

{
  "user": {
    "name": "John",
    "devices": {
      "2": {
        "os": "Android",
        "color": "blueish"
      },
      "1": {
        "os": "Android",
        "color": "redish"
      }
    }
  }
}

.

+4
1

persist , , . , , .

, id persist.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#merging-entities

:

, , , array (id = > newOrder,...), , , .

entity, integer. ,

+2

Source: https://habr.com/ru/post/1544497/


All Articles