I am quite new to Drupal and Drupal 8.

I have created a custom module that creates a custom content type. I am attempting to extract those entities and display them as JSON or XML.

I have read through the Entities Api on loading, querying, and rendering entities but I am struggling to find view_mode_name types :

$build = $view_builder->view($entity, 'view_mode_name', $language->getId()); 

Would I be able to do something like :

$build = $view_builder->view($entity, 'xml', $language->getId());

or does this only produce a 'render array' ? If this is the case then should I be looking at the Serializer Api ? If so would anyone be able to guide me in the right direction on using this ?

Here is my code so far :

public function display() {
// use the debug component

// get node -> testimonial content types
$entity_ids = \Drupal::entityQuery('node')
->condition('type', 'testimonial')
->execute(); // fetch

$node_storage = \Drupal::entityManager()->getStorage('node');

$data = $node_storage->loadMultiple($entity_ids);

$view_builder = \Drupal::entityManager()->getViewBuilder('node');

// render multiple 
return $view_builder->viewMultiple($data, 'xml');


1 Answer 1


View builders only display HTML/render arrays.

Look into the serialization/rest/hal modules if you want to extract the data of your entity, as you guessed already.

Note that REST in core only supports content entities at the moment, but I assume you have one of those.

Also, I'd recommend hal+json serialization, provided by the hal.module instead of the raw json seralization, as that can't deal with things like references properly.

  • Thanks for the advice Berdir. My entity is a content one so I should be good with the hal.module. Time to read up on the Symfony service container..
    – bart_88
    Commented Mar 3, 2015 at 6:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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