Created
June 30, 2021 15:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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