0

In Drupal 8, I'd like to retrieve JSON for multiple Rest export views, not just a single one. Example of data I want to see (cars and tires being two seperate content types):

{
    "cars": [
      { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102] },
      { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102] },
      { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103] }
    ],
    "tires": [
      { "nid": 100, "brand": "Michelin" },
      { "nid": 101, "brand": "Good Year" },
      { "nid": 102, "brand": "Dunlop" }
    ]
}

I can output the JSON fine seperately, so you visit one url to get cars, and another URL to get tires. But I can't figure out how to merge the two.

Can anyone help me figure this out, or anyone who can point me in the right direction to achieve this?

1

One option would be to create a parent view and use Views Field View to reference the other 2 views displays.

For example, /car-stuff would contain 2 fields, "Cars" and "Tires", each one is a views field view field referencing the relevant json view display. For the parent view, you'd need to add REST Export Nested so the JSON of the child views would be proper JSON instead of a string.

Alternative Solutions

There may be a cleaner way to achieve what you're after.The easiest would be to make 2 calls to retrieve the JSON feeds and join them on the front end.

Depending on your requirements, you could also retrieve the specific tires for each car type.

{
    "cars": [
        { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102],
            "tires": [
              { "nid": 100, "brand": "Michelin" },
              { "nid": 101, "brand": "Good Year" },
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102],
            "tires": [
              { "nid": 102, "brand": "Dunlop" }           
            ]
        },
        { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103],
            "tires": [
              { "nid": 103, "brand": "Unknown" }
            ]
        }
    ]
}

The above would also use Views Field View, with the child view Tires having a contextual filter of nid. For an example of this approach, see the answer I provided here.

  • Views - field - views doesn't really have a lot of documentation. Can you clarify how this should be created? – Mobile Bloke Sep 25 '17 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.