Hide a view programatically D8 I am trying to hide a view block if it has one or less results, i am doing this using the MYTHEME_preprocess_views_view function.

Here is the code

// Removes product range if only one product is availiable!
if($variables['view']-&gt;id() == 'brand_product_range') {
  if(count($variables['view']-&gt;result) &lt; 2) {
    // $variables['view']-&gt;destroy();
    // $variables['view']-&gt;setDisplay(false);
    // I want to hide block here!
  }
}


I managed to get the id of view block and number of results in the view, but I don't know how to hide the block, I tried the above methods but they are not working.
I assume your view is using a block display and you don't want the block to display at all if there is only 1 result.

In my opinion you are hooking in too late in the process to hide the view there. It is possible to hide it in the theme layer but I don't think it is the optimal approach.

There are a number of ways you can do it but here are a couple of ways using a hook in a custom module, not in a theme. (This is not an exhaustive list of options that you have.)

Option 1


Hook into the view execution process and tell the process that execution has failed, so it will not render the view.


For example:

use Drupal\views\ViewExecutable;

function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // If there is only 1 result set the failure condition so that
  // execution will not continue and the view will not display.
  if ($view-&gt;id() == 'VIEW_NAME') {
    if (count($view-&gt;result) == 1) {
      $view-&gt;build_info['fail'] = TRUE;
    }
  }
}


Option 2


Configure your view to have 'Hide block if the view output is empty' = Yes
Hook into the view execution process and clear the results when you don't want it to display.


For example:

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute().
 */
function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // Clear the results if there is only 1 result.
  // The view will then hide as it is configured to hide the
  // block if empty.
  if ($view-&gt;id() == 'VIEW_NAME') {
    if (count($view-&gt;result) == 1) {
      $view-&gt;result = array();
    }
  }
}


Note: Depending on how you decide to hide the view, if your views block is the only block in your region then be aware of this outstanding bug, which may cause your region to still display even though your block doesn't: https://www.drupal.org/project/drupal/issues/953034