Hi,

Is there anyway to get the result of a rest export in a view through programmatically?

I have created view in Drupal 8 with 2 pages and 2 rest exports. I would like to call one of the that rest exports from the code itself (instead of calling it as an API service using guzzle) to get the JSON response. Is there any better way for doing this?

Thanks

Comments

Boldizart’s picture

Check this answer. :)

franzy_’s picture

Hi,

I managed to take a JSON response of the view. But in my case, I am using the view's JSON repose to build another custom JSON response inside Custom Rest Resource. 

The problem when I render the view to get JSON response, I had to use RenderContext to prevent the early rending caching problem. 
But I can't figure how to merge both caching metadata. I am not getting any error but caching is not working only when I use view rendering methods.

Help me to figure this out.

Thanks.

// get method for Custom Rest Resource

get() {

//..........where I am adding code of view rendering for get JSON response of view

//Caching meta data for my custom array

$metadata['#cache'] = [

'contexts' => [

'url.query_args:date',

],

];

$response = new CacheableJsonResponse($result, 200);

$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($metadata));

return $response;
}
// end of get method

Without view rendering for getting JSON response, this works perfectly.

But when I add the following sections inside the above get method no errors but caching not working.
 

$responsenew = $renderer->executeInRenderContext($context, function () use ($renderer) {

$view = Views::getView('view_id');

$build = $view->preview('display_id');

$renderer->render($build);

return new HtmlResponse($build, 200);

});

f (!$context ->isEmpty()) {

$bubbleable_metadata = $context->pop();

$response->addCacheableDependency($bubbleable_metadata);

}