3

I have a page content type with fields Title, Body and Blocks field collection with fields Title and URL.

It might be field collection, paragraphs or entity reference, it doesn't matter because all of these types require relationship in views in order to get its fields.

I need to generate a JSON output with views that look like this:

{
  'title': 'This is my title',
  'body': '<p>lorem ipsum dolor sit amet.</p>',
  'blocks': [
    {
      'block_title': 'Block one',
      'block_url': 'www.example.com'
    },
    {
      'block_title': 'Block two',
      'block_url': 'www.site.com'
    },
  ]
}

What I managed to achieve so far, is this:

[
  {
    'title': 'This is my title',
    'body': '<p>lorem ipsum dolor sit amet.</p>',
    'block_title': 'Block one',
    'block_url': 'www.example.com'
  },
  {
    'title': 'This is my title',
    'body': '<p>lorem ipsum dolor sit amet.</p>',
    'block_title': 'Block two',
    'block_url': 'www.site.com'
  }
]

This is Drupal 8. Any suggestions?

closed as too broad by kiamlaluno Sep 26 '18 at 18:37

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

0

The data structure you want does not fit with what Views is supposed to provide. Views is intended only for generating lists. 'title' and 'body' are assumed to not be part of a list, so views has no configuration for defining single hardcoded values, and goes against how views works.

Your other option is to create a custom route with a node parameter (example) that returns a JsonResponse object with populated blocks property. So your code may look something like this (based on route parameter example above):

use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class ExampleController {
  function foo(NodeInterface $node) {
    $response = [
      'title' => $node->label(),
      'body' => $node->get('body')->first()->getValue(),
    ];

    $blocks = [];
    $block1 = $node->get('block')->get(0)->get('entity');

    $blocks[] = [
      'block_title' => $block1->label(),
      'block_url' => $block1->toUrl()->toString(),
    ];

    /* ... add the rest of the blocks ... */

    $response['blocks'] = $blocks;

    return new JsonResponse($response);
  }
}

The code will need to be adjusted according to your entity field setup.

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