Nylsoo Nylsoo - 2 months ago 20
JSON Question

Drupal 8 Headless - Group fields in view

I am trying to create a REST export in Drupal 8 from a node. At this moment the JSON response is like this:

[{
"title": "test 2",
"body": "<p>tets<\/p>",
"created": "10-09-2016 15:57",
"field_first_name": "John",
"field_last_name": "Doe"
}, {
"title": "test",
"body": "<p>test<\/p>"
"created": "10-09-2016 15:56",
"field_first_name": "John",
"field_last_name": "Doe"
}]


There are 2 fields,
field_first_name
and
field_last_name
, which are fields from the user who created the node. I wonder if it is possible to group those fields. So the response will look as something like this:

[{
"title": "test 2",
"body": "<p>tets<\/p>",
"created": "10-09-2016 15:57",
"user": {
"field_first_name": "John",
"field_last_name": "Doe"
}
}]


So is there a way to group fields by the entity they are from?

Answer

The default style for a REST view is the Serializer which ships with the rest module as a plugin (in Drupal core at /core/modules/rest).

You can alter the JSON output of your REST view by creating a views style plugin in a custom module, extending the plugin from the rest module. In the render() method you can write your own logic to alter the structure of your JSON.

So to group the fields by their entity, you can grab the entity bundle in the views related entities and restructure your output accordingly.

REST API through views in Drupal 8 - how to modify serializer may give you more insights on this matter.

Comments