Drupal - How do I programmatically render a view with contextual filters?

Basing on the code used by views_get_view_result(), I would use the following code, as code equivalent to the one you show in the question.

  $args = [$tid];
  $view = Views::getView('test_view');
  if (is_object($view)) {
    $view->setArguments($args);
    $view->setDisplay('block');
    $view->preExecute();
    $view->execute();
    $content = $view->buildRenderable('block', $args);
  }

/**
 * Return the rendered view with contextual filter.
 * @param string $viewId - The view machine name.
 * @param string $displayId - The display machine name.
 * @param array $arguments - The arguments to pass.
 * 
 * @return object $result
 */
function getView($viewId, $displayId, array $arguments)
{
    $result = false;
    $view = Views::getView($viewId);

    if (is_object($view)) {
        $view->setDisplay($displayId);
        $view->setArguments($arguments);
        $view->execute();

        // Render the view
        $result = \Drupal::service('renderer')->render($view->render());
    }

    return $result;
}

/**
 * Get json output.
 * @return array $data
 */
function jsonData() {
    $data = [];
    $viewId = 'rest_comments';
    $displayId = 'rest_export_1';
    $arguments = [$nid];

    // Get the view
    $result = getView($viewId, $displayId, $arguments);

    if(is_object($result)) {
        $json = $result->jsonSerialize();
        $data = json_decode($json);
    }

    return $data;
}


/**
 * Get the view object.
 * @return object $view
 */
function view() {
    $viewId = 'rest_comments';
    $displayId = 'rest_export_1';
    $arguments = [$nid];

    // Get the view
    $view = getView($viewId, $displayId, $arguments);

    return $view;
}

To get the actual JSON output of the REST Export display you can do something like this:

$view = \Drupal\views\Views::getView($view_id); 
$render_array = $view->buildRenderable('rest_export_display_name', $args);
$rendered = \Drupal::service('renderer')->renderRoot($render_array);
$json_string = $rendered->jsonSerialize();
$json_object = json_decode($rendered);

Tags:

Views

8