1

I want to print the output from a simple view in my custom module. But is doesnt work. I have tried many options from forums and stackoverflow. All of them print "array" instead of html-markup.

My controller:

class DefaultController extends ControllerBase {


    public function myfunc1() {

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

        $view->setDisplay('page_1');
        $view->preExecute();
        $view->execute();

        // $myresults = $view->preview();  = array
        // $myresults = $view->render();  = array
        $myresults = $view->result; // = array


        return array(
            '#title' => 'Hello World!',
            '#markup' => $myresults,
        );
    }
}

How can I print the result/output of a view programmatically?

I dont want to make it without "embed view" , because I want to set some exposed filters later.

3

Views implements its own render element type (Drupal\views\Element\View), which you can use like so:

return [
  '#title' => 'Hello world',
  'view' => [
    '#type' => 'view',
    '#name' => 'myfirstview',
    '#display_id' => 'page_1',
    '#arguments' => ['foo', 'bar'],
    '#embed' => TRUE,
  ],
];

If you need to manipulate the View before rendering it, (you mentioned exposed filters), you can do that first and pass along the object:

$view = Views::getView('myfirstview');
$view->setFoo('bar');

return [
  '#type' => 'view',
  '#name' => 'myfirstview',
  '#view' => $view,
  '#display_id' => 'page_1',
  '#embed' => TRUE,
];
0

Notes: The View has to be a block. Exposed filters can be added but will not be displayed on your page. You can set them in your page, eg for a 'severity' field:

$filters = $view->getDisplay()->getOption('filters');
$filters['severity']['value'] = [0,1,2,3,4,5,6]; // include a set of values.
$view->getDisplay()->overrideOption('filters', $filters);

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.