Skip to content

Instantly share code, notes, and snippets.

@lincoln-chawora
Created June 30, 2021 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lincoln-chawora/3a0f1c53b15b575058d5494e3e0422df to your computer and use it in GitHub Desktop.
Save lincoln-chawora/3a0f1c53b15b575058d5494e3e0422df to your computer and use it in GitHub Desktop.
How to render a view in code and check if it's empty
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
/**
* Implements hook_preprocess_HOOK().
*/
function YOUR_MODULE_NAME_preprocess_HOOK(&$variables) {
$some_entity_id = 10;
$view = Views::getView('name_of_view');
if (is_object($view) && $most_linked_profiles_view instanceof ViewExecutable) {
$view->setArguments([$some_entity_id]);
$view->setDisplay('block_1');
$view->preExecute();
$view->execute();
if (!empty($view->result)) {
$variables['some_var_name_to_access_in_twig'] = $view->buildRenderable('block_1', [$some_entity_id]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment